从Flask上下文处理器读取URL变量 [英] Read URL variables from Flask context processor

查看:116
本文介绍了从Flask上下文处理器读取URL变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

现在,我要注册一个上下文处理器,它只在使用<$ c $调用视图函数时才运行

    c> post_id 作为参数
  1. 以某种方式访问​​ post_id ,而不必重新解析重新整理网址,例如 re.match

本质上:

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

如果我可以访问 ** kwargs 在这个例子中传递给 show_post 来自上下文处理器我可以做到这一点,但是我发现没有办法做到这一点。任何想法?

解决方案

使用 request.view_args

  @ app.context_processor 
def provide_foo():$ b $如果request.view_args中的post_id:
post_id = request.view_args [post_id]
return {bar :some_function(post_id)}


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. 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

essentially:

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

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?

解决方案

Use 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天全站免登陆