【问题标题】:Get variables parsed from Flask URL获取从 Flask URL 解析的变量
【发布时间】:2014-02-20 23:22:17
【问题描述】:

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

@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来自上下文处理器我可以做到,但我没有办法做到这一点。有什么想法吗?

【问题讨论】:

    标签: flask


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2016-05-13
      • 2022-07-07
      • 2014-03-14
      • 1970-01-01
      • 2011-09-28
      • 1970-01-01
      相关资源
      最近更新 更多