In Flask, when I have several routes for the same function, how can I know which route is used at the moment?
For example:
@app.route("/antitop/") @app.route("/top/") @requires_auth def show_top(): ....
How can I know, that now route was called using /top/
or /antitop/
?
UPDATE
I know about request.path
I don't want use it, because the request can be rather complex, and I want repeat the routing logic in the function. I think that the solution with url_rule
it the best one.
You can set values per route. @app. route("/antitop/", defaults={'_route': 'antitop'}) @app. route("/top/", defaults={'_route': 'top'}) @requires_auth def show_top(_route): # use _route here ...
Routing in Flask The route() decorator in Flask is used to bind an URL to a function. As a result when the URL is mentioned in the browser, the function is executed to give the result.
App routing is used to map the specific URL with the associated function that is intended to perform some task. It is used to access some particular page like Flask Tutorial in the web application.
The @ is telling Python to decorate the function index() with the decorator defined in app. route() . Basically, a decorator is a function that modifies the behaviour of another function. As a toy example, consider this.
Simply use request.path
.
from flask import request ... @app.route("/antitop/") @app.route("/top/") @requires_auth def show_top(): ... request.path ...
the most 'flasky' way to check which route triggered your view is, by request.url_rule
.
from flask import request rule = request.url_rule if 'antitop' in rule.rule: # request by '/antitop' elif 'top' in rule.rule: # request by '/top'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With