Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using url_for across blueprints

Tags:

python

flask

Does url_for work across blueprints?

/flaskapp
    /runserver.py           (from server import app; app.run(debug=True))
    /server
        /__init__.py        (app = Flask(__name__))
        /pages
            /__init__.py    ('pages' blueprint)
        /users
            /__init__.py    ('users' blueprint)

in server/__init__.py:

from server.pages import pages
from server.users import users

app = Flask(__name__)

app.register_blueprint(pages)
app.register_blueprint(users)

in server/pages/__init__.py:

pages = Blueprint('pages', __name__)

@pages.route('/')
def index(): return '<h1>Index</h1>'

in server/users/__init__.py:

users = Blueprint('users', __name__)

@users.route('/login')
def login():
    ...
    return redirect(url_for('pages.index'))
                    ^^^^^^^^^^^^^^^^^^^^^^

The url_for call raises BuildError: ('pages.index', {}, None) What would be a way to get to 'pages.index'?

(I tried importing the module, but that didn't work)

like image 916
arunjitsingh Avatar asked Oct 06 '13 11:10

arunjitsingh


1 Answers

Short Answer: Yes

Long(ish) Answer:

As best I can tell, you're organizing your app the way you should.

I've recreated your setup (albeit in a single file), which you can checkout here. This code runs on my machine.

https://gist.github.com/enlore/80bf02346d6cabcba5b1

In flask, you can access a given view function with a relative endpoint (.login) from within the owning blueprint, or an via an absolute one (user.login) anywhere.

My money is on you having a typo in a view function name.

Like Mark Hildreth said in the comments, a great way to debug your problem would be to take a look at your url map.

>>> from app import app
>>> app.url_map
Map([<Rule '/login' (HEAD, OPTIONS, GET) -> user.login>,
 <Rule '/' (HEAD, OPTIONS, GET) -> pages.index>,
 <Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>])
>>>
like image 73
nothankyou Avatar answered Sep 25 '22 04:09

nothankyou