url_for Builderror in flask extension with pluggable views

痴心易碎 提交于 2019-12-11 10:42:20

问题


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?

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()

回答1:


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'))


来源:https://stackoverflow.com/questions/13345030/url-for-builderror-in-flask-extension-with-pluggable-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!