从Flask上下文处理器读取URL变量

maa*_*kle 10 flask

假设我有一个带有可变部分的简单路径:

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

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

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

实质上:

@app.context_processor
def foo():
    post_id = ???
    return {'bar': some_function(post_id)}
Run Code Online (Sandbox Code Playgroud)

如果我可以上下文处理器访问此示例中的**kwargs传递给我,我可以做到,但我发现无法做到这一点.有任何想法吗?show_post

Sea*_*ira 12

用途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)}
Run Code Online (Sandbox Code Playgroud)