Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: get current route

Tags:

python

url

flask

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.

like image 417
Igor Chubin Avatar asked Feb 01 '14 13:02

Igor Chubin


People also ask

How do I find my current route in Flask?

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 ...

What does .route do in Flask?

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.

What is app route () in Python?

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.

What does @APP mean in Flask?

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.


2 Answers

Simply use request.path.

from flask import request  ...  @app.route("/antitop/") @app.route("/top/") @requires_auth def show_top():     ... request.path ... 
like image 187
falsetru Avatar answered Oct 04 '22 06:10

falsetru


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' 
like image 36
thkang Avatar answered Oct 04 '22 05:10

thkang