Flask: get current route

PythonUrlFlask

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

Simply use request.path.

from flask import request

...

@app.route("/antitop/")
@app.route("/top/")
@requires_auth
def show_top():
    ... request.path ...

Solution 2 - Python

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'

Solution 3 - Python

Another option is to use endpoint variable:

@app.route("/api/v1/generate_data", methods=['POST'], endpoint='v1')
@app.route("/api/v2/generate_data", methods=['POST'], endpoint='v2')
def generate_data():
    version = request.endpoint
    return version

Solution 4 - Python

If you want different behaviour to each route, the right thing to do is create two function handlers.

@app.route("/antitop/")
@requires_auth
def top():
    ...

@app.route("/top/")
@requires_auth
def anti_top():
    ...

In some cases, your structure makes sense. 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
    ...

Solution 5 - Python

It seems to me that if you have a situation where it matters, you shouldn't be using the same function in the first place. Split it out into two separate handlers, which each call a common fiction for the shared code.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIgor ChubinView Question on Stackoverflow
Solution 1 - PythonfalsetruView Answer on Stackoverflow
Solution 2 - PythonthkangView Answer on Stackoverflow
Solution 3 - PythonmarcinkuzminskiView Answer on Stackoverflow
Solution 4 - PythoniurisilvioView Answer on Stackoverflow
Solution 5 - PythonDaniel RosemanView Answer on Stackoverflow