Python 传递参数时重定向
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17057191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
redirect while passing arguments
提问by limp_chimp
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:
如果 foo.html 包含{{ messages['main'] }},页面将显示hello。但是如果有一条通往 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:
在这种情况下,访问 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'
So, how can I get that messagesvariable to be passed to the fooroute, so that I don't have to just rewrite the same logic code that that route computes before loading it up?
那么,我如何才能将该messages变量传递给foo路由,这样我就不必在加载之前重写该路由计算的相同逻辑代码?
采纳答案by Tommi Komulainen
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:
您可以将消息作为显式 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))
(encoding the session variable might not be necessary, flask may be handling it for you, but can't recall the details)
(可能不需要对会话变量进行编码,flask 可能会为您处理,但不记得详细信息)
Or you could probably just use Flask Message Flashingif you just need to show simple messages.
或者,如果您只需要显示简单的消息,您可以只使用Flask Message Flashing。
回答by Ben
I'm a little confused. "foo.html" is just the name of your template. There's no inherent relationship between the route name "foo" and the template name "foo.html".
我有点困惑。“foo.html”只是您模板的名称。路由名称“foo”和模板名称“foo.html”之间没有内在关系。
To achieve the goal of not rewriting logic code for two different routes, I would just define a function and call that for both routes. I wouldn't use redirect because that actually redirects the client/browser which requires them to load two pages instead of one just to save you some coding time - which seems mean :-P
为了实现不为两条不同的路由重写逻辑代码的目标,我只需定义一个函数并为两条路由调用它。我不会使用重定向,因为这实际上会重定向客户端/浏览器,这需要它们加载两个页面而不是一个页面,只是为了节省一些编码时间 - 这似乎意味着 :-P
So maybe:
所以也许:
def super_cool_logic():
# execute common code here
@app.route("/foo")
def do_foo():
# do some logic here
super_cool_logic()
return render_template("foo.html")
@app.route("/baz")
def do_baz():
if some_condition:
return render_template("baz.html")
else:
super_cool_logic()
return render_template("foo.html", messages={"main":"Condition failed on page baz"})
I feel like I'm missing something though and there's a better way to achieve what you're trying to do (I'm not really sure what you're trying to do)
我觉得我错过了一些东西,但有更好的方法来实现你想要做的事情(我不确定你想要做什么)
回答by Nick Woodhams
I found that none of the answers here applied to my specific use case, so I thought I would share my solution.
我发现这里的答案都不适用于我的特定用例,所以我想我会分享我的解决方案。
I was looking to redirect an unauthentciated user to public version of an app page with any possible URL params. Example:
我希望使用任何可能的 URL 参数将未经身份验证的用户重定向到应用程序页面的公共版本。例子:
/app/4903294/my-great-car?email=coolguy%40gmail.com to
/ app/4903294/my-great-car?email=coolguy%40gmail.com 到
/public/4903294/my-great-car?email=coolguy%40gmail.com
/ public/4903294/my-great-car?email=coolguy%40gmail.com
Here's the solution that worked for me.
这是对我有用的解决方案。
return redirect(url_for('app.vehicle', vid=vid, year_make_model=year_make_model, **request.args))
Hope this helps someone!
希望这对某人有帮助!
回答by saltydog
I want to mention that url_forcannot be used until it is added to the flask imports!
我想提一下,url_for在将其添加到烧瓶导入之前无法使用!
I spent an hour trying to find out why it would not work as no one mentioned that in several websites!!!
我花了一个小时试图找出为什么它不起作用,因为没有人在几个网站上提到过!!!
Add url_forto the list of imports like this:
添加url_for到这样的导入列表中:
from flask import Flask, render_template, request, redirect, session, url_for

