Question

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()
Was it helpful?

Solution

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'))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top