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

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

问题描述

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

如果foo.html包含 {{messages [ 'main']}} ,页面将显示 hello 。但是,如果有一条路线导致foo:

pre $ app $($ / $)
def do_foo():
#在这里做一些逻辑
return render_template(foo.html)

在这种情况下,如果我想让逻辑发生的话,唯一可以通过重定向来获得foo.html的方法是:


$ b $

  @ app.route(/ baz)
def do_baz():
如果some_condition:
返回render_template(baz.html)
else:
返回重定向(/ foo,messages = {main:条件在页面baz上失败)}
# TypeError:redirect()得到了一个意想不到的关键字参数'messages'

code> messages 变量传递给 foo 路由,所以我不必重写相同的逻辑代码该路线计算之前加载它?

解决方案

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

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $信息= )}
session ['messages'] = messages
return redirect(url_for('.do_foo',messages = messages))

@ app.route( '/ foo')
def do_foo():
messages = request.args ['messages']#对应的url_for()
messages = session ['messages']#session
return render_template(foo.html,messages = json.loads(messages))

(编码会话变量可能不是必要的,烧瓶可能正在处理它,但不记得的细节)

或者你可能只是使用 Flask消息闪烁,如果你只是需要显示简单的消息。


In flask, I can do this:

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

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

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'

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?

解决方案

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

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

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

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