具有可插入视图的烧瓶扩展中的url_for Builderror [英] url_for Builderror in flask extension with pluggable views
问题描述
我正在为flask构建一个简单的扩展,但是url_for函数无法在扩展中构建url时遇到了问题.
I am building a simple extension for flask and have a problem with the url_for function not being able to build the urls within the extension.
有人可以帮我弄清楚我在这里想念的是什么吗?
Can somebody help me figure out what I am missing here?
我简化了代码以演示问题(所有url_for调用均引发werkzeug BuildError异常):
I simplified the code to demonstrate the issue (all of the url_for calls raise a werkzeug BuildError exception):
import flask
import flask.views
import logging
logging.basicConfig(level=logging.DEBUG)
class MyFlaskExt(object):
def __init__(self, app=None):
if app is not None:
self.init_app(app)
def init_app(self, app):
self.blueprint = flask.Blueprint('myext', __name__, static_folder='static', template_folder='templates')
self.blueprint.add_url_rule('/', view_func=RootView.as_view('root'), endpoint='root')
self.blueprint.add_url_rule('/var/<somevar>', view_func=VarView.as_view('var'), endpoint='var')
self.blueprint.add_url_rule('/novar', view_func=NoVarView.as_view('novar'), endpoint='novar')
app.register_blueprint(self.blueprint)
class RootView(flask.views.View):
def dispatch_request(self):
logging.debug(flask.url_for('novar'))
logging.debug(flask.url_for('novar', _external=True))
return flask.redirect(flask.url_for('var', somevar='test'))
class VarView(flask.views.View):
def dispatch_request(self, somevar):
return "SUCCESS! ({})".format(somevar)
class NoVarView(flask.views.View):
def dispatch_request(self):
return "SUCCESS!"
if __name__ == '__main__':
app = flask.Flask(__name__)
app.debug = True
my_ext = MyFlaskExt()
my_ext.init_app(app)
logging.debug(app.url_map)
app.run()
推荐答案
Blueprint
端点以 Blueprint
的名称注册.如果我没记错的话,您将需要在 url_for
调用之前加上".(如果它们都将在同一蓝图下运行)或使用全名:
Blueprint
endpoints are registered under the name of the Blueprint
. If I remember correctly you will either need to prepend your url_for
calls with "." (if they will all be operating under the same blueprint) or use the full name:
def dispatch_request(self):
logging.debug(flask.url_for('.novar'))
logging.debug(flask.url_for('.novar', _external=True))
return flask.redirect(flask.url_for('.var', somevar='test'))
这篇关于具有可插入视图的烧瓶扩展中的url_for Builderror的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!