在python flask中,如何获取路由函数外的路径参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41492721/
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
In python flask, how do you get the path parameters outside of the route function?
提问by yigal
In flask, you can define path parameters like so:
在烧瓶中,您可以像这样定义路径参数:
@app.route('/data/<section>')
def data(section):
print section
In The above example, you can access the section variable only from the data endpoint (unless you pass it around in function parameter)
在上面的例子中,你只能从数据端点访问 section 变量(除非你在函数参数中传递它)
You can also get the query parameters by accessing the request object. this works from the endpoint function as well as any other called function, without needing to pass anything around
您还可以通过访问请求对象来获取查询参数。这适用于端点函数以及任何其他被调用的函数,无需传递任何东西
request.args['param_name']
my question is: is in possible to access the path parameter (like section above) in the same way as the query parameters?
我的问题是:是否可以以与查询参数相同的方式访问路径参数(如上面的部分)?
回答by julienc
It's possible to use request.view_args
.
The documentationdefines it this way:
可以使用request.view_args
. 该文档定义了这种方式:
A dict of view arguments that matched the request.
与请求匹配的视图参数的字典。
Here's an example:
下面是一个例子:
@app.route("/data/<section>")
def data(section):
assert section == request.view_args['section']