重定向回 Flask [英] Redirect back in Flask

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

问题描述

我有一个名为 Item 的数据库表.项目有一个 status 属性,可以是

I have a DB Table called Item. Item has a status attribute, that can be either of

new
todo
doing
done

在我的网站上,我有两个显示项目表的视图.

On my website I have two views showing tables of Item.

  • 视图 1 显示所有项目(带有状态栏).
  • View 2 only 显示状态为 todo 的项目.
  • View 1 shows all Items (with a status column).
  • View 2 only shows Items with the status todo.

根据项目状态,用户可以执行某些操作(移至待办事项"、移至正在做的"、移至已完成").

Depending on the Item status, there are certain actions a user can perform ("move to todo", "move to doing", "move to done").

如果您考虑视图 1 和视图 2,它们都有一个共同点,即它们都包含状态为 todo 的项目.所以在两者上我都有一个 Button 链接到一个名为

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

/Item/<id>/moveToDoing

其中 id - 项目的状态设置为正在执行".

where id - Item's status is set to "doing".

现在我希望将用户重定向回他单击按钮的位置(视图 1 或视图 2).

Now I want the user to be redirected back to where he clicked the button (View 1 or View 2).

我的问题是:

  1. 如何用 Flask 做到这一点?我觉得http://flask.pocoo.org/snippets/62/ 不是我所需要的,因为我这里没有带有公式的 POST 请求.(我应该吗?)
  2. 我这样做是否正确,或者是否有关于如何正常解决该问题的约定?
  1. 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?)
  2. Am I doing this the right way or is there a convention on how to normally solve that?

推荐答案

我正在使用这里推荐的辅助函数:http://flask.pocoo.org/docs/reqcontext/

I'm using the helper function which is recommended here: http://flask.pocoo.org/docs/reqcontext/

def redirect_url(default='index'):
    return request.args.get('next') or 
           request.referrer or 
           url_for(default)

在视图中使用它

def some_view():
    # some action
    return redirect(redirect_url())

在没有任何参数的情况下,它会将用户重定向回他的来源(request.referrer).您可以添加获取参数 next 来指定一个 url.例如,这对 oauth 很有用.

Without any parameters it will redirect the user back to where he came from (request.referrer). You can add the get parameter next to specify a url. This is useful for oauth for example.

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.

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

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