传递参数时重定向 [英] redirect while passing arguments

查看:83
本文介绍了传递参数时重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In flask, I can do this:

render_template("foo.html", messages={'main':'hello'})

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

And if foo.html contains {{ messages['main'] }}, the page will show hello. But what if there's a route that leads to foo:

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

在这种情况下,如果我仍然希望这种逻辑发生,那么进入foo.html的唯一方法是通过redirect:

In this case, the only way to get to foo.html, if I want that logic to happen anyway, is through a 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'

那么,如何获取该messages变量以传递给foo路由,这样我不必在加载该路由之前就重写该路由计算出的相同逻辑代码?

So, how can I get that messages variable to be passed to the foo route, so that I don't have to just rewrite the same logic code that that route computes before loading it up?

推荐答案

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

You could pass the messages as explicit URL parameter (appropriately encoded), or store the messages into session (cookie) variable before redirecting and then get the variable before rendering the template. For example:

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

(可能不需要对会话变量进行编码,flask可能正在为您处理它,但无法调用详细信息)

(encoding the session variable might not be necessary, flask may be handling it for you, but can't recall the details)

或者,如果您只需要显示烧瓶消息闪烁,则可以使用简单的消息.

Or you could probably just use Flask Message Flashing if you just need to show simple messages.

这篇关于传递参数时重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆