Python Flask:获取当前路线
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21498694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Flask: get current route
提问by Igor Chubin
In Flask, when I have several routes for the same function, how can I know which route is used at the moment?
在 Flask 中,当我有多个路由用于同一功能时,我如何知道当前使用的是哪条路由?
For example:
例如:
@app.route("/antitop/")
@app.route("/top/")
@requires_auth
def show_top():
....
How can I know, that now I was called using /top/or /antitop/?
我怎么知道,现在我被调用了使用/top/or /antitop/?
UPDATE
更新
I know about request_pathI 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_ruleit the best one.
我知道request_path我不想使用它,因为请求可能相当复杂,我想在函数中重复路由逻辑。我认为它的解决方案url_rule是最好的。
采纳答案by thkang
the most 'flasky' way to check which route triggered your view is, by request.url_rule.
检查哪条路线触发您的视图的最“灵活”的方法是通过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'
回答by falsetru
Simply use request.path.
只需使用request.path.
from flask import request
...
@app.route("/antitop/")
@app.route("/top/")
@requires_auth
def show_top():
... request.path ...
回答by Daniel Roseman
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.
在我看来,如果您遇到重要的情况,您首先不应该使用相同的功能。将其拆分为两个独立的处理程序,每个处理程序为共享代码调用一个共同的虚构。
回答by iurisilvio
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
...
回答by marcinkuzminski
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

