URL building with Flask and non-unique handler nam

2019-01-30 16:40发布

问题:

Flask provides a url_for function to generate URLs to handlers based on the URL pattern. But this would imply that the handler functions must have unique names across the entire application. Is that correct?

Example

Module A has a handler index:

@app.route('/')
def index(): pass

And Module B has another handler index:

@app.route('/anotherindex')
def index(): pass

How to distinguish the handlers called index when building URLs?

url_for('index')

回答1:

I don't know how you could do with all the views routed by the same module.

What I usually do is separate my views in different modules (like you did with module A and B), and register them as blueprints, after that, when using the url_for() function, you can prefix the view name with your blueprint name and then avoid conflicts and potential problems.

Here is an example:

main_views.py:

from flask import Blueprint
main = Blueprint('main', __name__)

@main.route('/')
def index():
    pass

admin_views.py:

from flask import Blueprint
admin = Blueprint('admin', __name__)

@admin.route('/admin')
def index():
    pass

application.py:

from flask import Flask
from main_views import main
from admin_views import admin

app = Flask('my_application')
app.register_blueprint(main)
app.register_blueprint(admin)

Now, to access the 2 index views and still distinguish one from the other, just use url_for('main.index') or url_for('admin.index')

EDIT:

Just one more useful details about routing using blueprints, when registering the blueprint, you can pass a url_prefix argument, that will apply to every view within this blueprint.

For example, given the following code:

admin_views.py

from flask import Blueprint
admin = Blueprint('admin', __name__)

@admin.route('/')
def index():
    pass

@admin.route('/logout')
def logout():
    pass

application.py:

from flask import Flask
from admin_views import admin

app = Flask('my_application')
app.register_blueprint(admin, url_prefix='/admin')

The 2 views would be available at the URL /admin/ and /admin/logout