获取从 Flask URL 解析的变量 [英] Get variables parsed from Flask URL

查看:24
本文介绍了获取从 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

  1. 仅在以post_id为参数调用视图函数时运行
  2. 以某种方式可以访问 post_id,而无需重新解析 URL,例如重新匹配
  1. Only runs when the view function is called with post_id as a parameter
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆