获取从Flask URL解析的变量 [英] Get variables parsed from Flask URL
本文介绍了获取从Flask URL解析的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一条带有可变部分的简单路线:
Suppose I have a simple route with a variable part:
@app.route('/post/<int:post_id>')
def show_post(post_id):
return 'Post %d' % post_id
现在我要注册一个上下文处理器
Now I want to register a context processor that
- 仅在以
post_id
作为参数调用视图函数时运行 - 以某种方式可以访问
post_id
,而不必通过例如重新重新解析URL.re.match
- Only runs when the view function is called with
post_id
as a parameter - somehow has access to
post_id
, without having to re-parse the URL all over again with e.g.re.match
本质上:
@app.context_processor
def foo():
post_id = ???
return {'bar': some_function(post_id)}
如果我可以从上下文处理器访问在本示例 中传递给show_post
的**kwargs
,则可以执行此操作,但是我找不到这样做的方法.有什么想法吗?
If I could access the **kwargs
passed to show_post
in this example from the context processor I could do it, but I've found no way to do that. Any ideas?
推荐答案
使用 request.view_args
:
@app.context_processor
def provide_foo():
if "post_id" in request.view_args:
post_id = request.view_args["post_id"]
return {"bar": some_function(post_id)}
这篇关于获取从Flask URL解析的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文