Python 重定向回 Flask
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14277067/
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 back in Flask
提问by kadrian
I have a DB Table called Item. Item has a statusattribute, that can be either of
我有一个名为 Item 的数据库表。项目有一个status属性,可以是
new
todo
doing
done
On my website I have two views showing tables of Item.
在我的网站上,我有两个视图显示项目表。
- View 1 shows allItems (with a status column).
- View 2 onlyshows Items with the status
todo.
- 视图 1 显示所有项目(带有状态列)。
- 视图 2仅显示状态为 的项目
todo。
Depending on the Item status, there are certain actions a user can perform ("move to todo", "move to doing", "move to done").
根据项目状态,用户可以执行某些操作(“移至待办事项”、“移至正在做的”、“移至已完成”)。
If you consider View 1 and View 2, they both have in common that they contain items with the status todo. So on both I have a Button linking to a URL called
如果考虑视图 1 和视图 2,它们的共同点是它们都包含状态为 的项目todo。所以在两者上我都有一个 Button 链接到一个名为的 URL
/Item/<id>/moveToDoing
where id - Item's status is set to "doing".
其中 id - 项目的状态设置为“正在执行”。
Now I want the user to be redirected back to where he clicked the button (View 1 or View 2).
现在我希望用户被重定向回他单击按钮的位置(视图 1 或视图 2)。
My questions are:
我的问题是:
- How to do this with Flask? I feel http://flask.pocoo.org/snippets/62/is not quite what I need, because I have no POST request with a formular here. (should I?)
- Am I doing this the right way or is there a convention on how to normally solve that?
- 如何用 Flask 做到这一点?我觉得 http://flask.pocoo.org/snippets/62/不是我所需要的,因为我这里没有带有公式的 POST 请求。(我是不是该?)
- 我这样做是正确的方式还是有关于如何正常解决这个问题的约定?
采纳答案by Smoe
I'm using the helper function which is recommended here: http://flask.pocoo.org/docs/reqcontext/
我正在使用这里推荐的辅助函数:http: //flask.pocoo.org/docs/reqcontext/
def redirect_url(default='index'):
return request.args.get('next') or \
request.referrer or \
url_for(default)
Use it in in the view
在视图中使用它
def some_view():
# some action
return redirect(redirect_url())
Without any parameters it will redirect the user back to where he came from (request.referrer).
You can add the get parameter nextto specify a url. This is useful for oauth for example.
没有任何参数,它会将用户重定向回他来自 ( request.referrer) 的地方。您可以添加 get 参数next来指定 url。例如,这对 oauth 很有用。
instagram.authorize(callback=url_for(".oauth_authorized",
next=redirect_url(),
_external=True))
I also added a default view if there should be no referrer for some reason
如果由于某种原因不应该有推荐人,我还添加了一个默认视图
redirect_url('.another_view')
redirect_url('.another_view')
The snippet you linked basically does the same but more secure by ensuring you cannot get redirected to a malicious attacker's page on another host.
您链接的代码段基本相同,但通过确保您不会被重定向到另一台主机上的恶意攻击者页面而更安全。

