URL building with Flask and non-unique handler names

我只是一个虾纸丫 提交于 2019-12-18 10:14:23

问题


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



来源:https://stackoverflow.com/questions/6957396/url-building-with-flask-and-non-unique-handler-names

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