Flask-login不会重定向到上一页

won*_*ile 9 python redirect login flask flask-login

考虑到这一点,我已经看到了很多问题,但未能解决我的问题.我有一个带烧瓶登录的Flask应用程序用于会话管理.而且,当我尝试在没有登录的情况下查看页面时,我会被重定向到一个形式的链接/login/?next=%2Fsettings%2F

问题是,据我所知,"下一个"参数保存了我实际需要的网站部分,但是当向登录表单提交请求时,它是通过完成的POST,所以这个论点不再存在可供我重定向到.

我试图使用Request.path申请(网址),但都只是返回/login/的请求URL /路径,而不是实际的/login/?next=xxx.

我的登录方法如下:

@app.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        #getting the user
        user = User.get(request.form['username'])
        if user.user is None:
            return redirect('/login/')
        #actual login proces
        if user and check_password_hash(user.user.password, request.form['password']):
            login_user(user, remember=remember)
            #the redirection portion of the login process
            return redirect(request.path or ("/")) # I tried various options there but without success, like request.args['next'] and such

        return redirect('/login/')

    else:
        return redirect('/')
Run Code Online (Sandbox Code Playgroud)

谢谢

Mar*_*eth 18

request.path不是你想要的.它返回URL的实际路径.因此,如果您的URL是/a/?b=c,则request.path返回/a,而不是c您期望的那样.

next参数?位于URL之后,因此它是"查询字符串"的一部分.Flask已经为您解析了查询字符串中的项目,您可以使用它来检索这些值request.args.如果您发送到URL的请求/a/?b=c,做request.args.get('b'),你会收到"c".

所以,你想要使用request.args.get('next').文档在一个示例中显示了它的工作原理.

另外要记住的是,当您在HTML中创建登录表单时,您不希望设置"action"属性.所以,不要这样做..

<form method="POST" action="/login">
    ...
</form>
Run Code Online (Sandbox Code Playgroud)

这将导致发出POST请求/login,而不是/login/?next=%2Fsettings%2F意味着您的next参数不会成为查询字符串的一部分,因此您将无法检索它.您想要省略"action"属性:

<form method="POST">
    ...
</form>
Run Code Online (Sandbox Code Playgroud)

这将导致表单发布到当前URL(应该是/login/?next=%2Fsettings%2f).

  • 我什至没想到检查表单标签中的`action="/"`。呸!:) 非常感谢! (2认同)