传递参数时重定向

lim*_*imp 43 python flask

在烧瓶中,我可以这样做:

render_template("foo.html", messages={'main':'hello'})
Run Code Online (Sandbox Code Playgroud)

如果foo.html包含{{ messages['main'] }},页面将显示hello.但是,如果有一条通往foo的路线怎么办:

@app.route("/foo")
def do_foo():
    # do some logic here
    return render_template("foo.html")
Run Code Online (Sandbox Code Playgroud)

在这种情况下,获取foo.html的唯一方法是,如果我希望无论如何都要发生这种逻辑,那就是通过redirect:

@app.route("/baz")
def do_baz():
    if some_condition:
        return render_template("baz.html")
    else:
        return redirect("/foo", messages={"main":"Condition failed on page baz"}) 
        # above produces TypeError: redirect() got an unexpected keyword argument 'messages'
Run Code Online (Sandbox Code Playgroud)

那么,我怎样才能将该messages变量传递给foo路由,这样我就不必在加载之前重写该路由计算的相同逻辑代码?

Tom*_*nen 68

您可以将消息作为显式URL参数(适当编码)传递,或者session在重定向之前将消息存储到(cookie)变量中,然后在呈现模板之前获取变量.例如:

def do_baz():
    messages = json.dumps({"main":"Condition failed on page baz"})
    session['messages'] = messages
    return redirect(url_for('.do_foo', messages=messages))

@app.route('/foo')
def do_foo():
    messages = request.args['messages']  # counterpart for url_for()
    messages = session['messages']       # counterpart for session
    return render_template("foo.html", messages=json.loads(messages))
Run Code Online (Sandbox Code Playgroud)

(可能没有必要编码会话变量,烧瓶可能会为您处理它,但无法回忆起细节)

或者你可以只使用Flask Message Flashing,如果你只需要显示简单的消息.

  • +1,消息闪烁绝对是要走的路. (4认同)
  • 这里会话的问题是你可能会遇到竞争条件:如果有人同时请求同一页面两次,他们可能会收到错误的消息。 (2认同)

Nic*_*ams 8

我发现这里的答案都不适用于我的特定用例,所以我想我会分享我的解决方案。

我希望使用任何可能的 URL 参数将未经身份验证的用户重定向到应用程序页面的公共版本。例子:

/ app /4903294/my-great-car?email=coolguy%40gmail.com 到

/ public /4903294/my-great-car?email=coolguy%40gmail.com

这是对我有用的解决方案。

return redirect(url_for('app.vehicle', vid=vid, year_make_model=year_make_model, **request.args))
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助某人!