URL building with Flask and non-unique handler names URL building with Flask and non-unique handler names flask flask

URL building with Flask and non-unique handler names


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 Blueprintmain = Blueprint('main', __name__)@main.route('/')def index():    pass

admin_views.py:

from flask import Blueprintadmin = Blueprint('admin', __name__)@admin.route('/admin')def index():    pass

application.py:

from flask import Flaskfrom main_views import mainfrom admin_views import adminapp = 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 Blueprintadmin = Blueprint('admin', __name__)@admin.route('/')def index():    pass@admin.route('/logout')def logout():    pass

application.py:

from flask import Flaskfrom admin_views import adminapp = Flask('my_application')app.register_blueprint(admin, url_prefix='/admin')

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