获取从 Flask URL 解析的变量



假设我有一条带有变量部分的简单路由:

@app.route('/post/<int:post_id>')
def show_post(post_id):
    return 'Post %d' % post_id

现在我想注册一个上下文处理器

  1. 仅在以 post_id 作为参数调用视图函数时运行
  2. 以某种方式可以访问post_id,而不必重新解析URL,例如 re.match

本质上:

@app.context_processor
def foo():
    post_id = ???
    return {'bar': some_function(post_id)}

如果我可以从上下文处理器访问此示例中传递给show_post**kwargs,我可以做到这一点,但我找不到这样做的方法。有什么想法吗?

使用 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)}

最新更新