gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:35:56 24 4
gpt4 key购买 nike

我已经看到不少与此有关的问题,但无法解决我的问题。我有一个带有 flask-login 的 Flask 应用程序,用于 session 管理。而且,当我尝试在不登录的情况下查看页面时,我会被重定向到 /login/?next=%2Fsettings%2F

形式的链接

问题是,据我所知,“下一个”参数包含我实际需要的网站部分,但是当向登录表单提交请求时,它是通过 POST 完成的,因此我无法再将此参数重定向到。

我尝试使用来自 RequestRequest.path (和 url)但两者都只返回 /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('/')

谢谢

最佳答案

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')。文档 shows how this works in an example .

另一件要记住的事情是,当您在 HTML 中创建登录表单时,您不想设置“action”属性。所以,不要这样做..

<form method="POST" action="/login">
...
</form>

这将导致向 /login 发出 POST 请求,而不是 /login/?next=%2Fsettings%2F,这意味着您的下一个 code> 参数不会成为查询字符串的一部分,因此您将无法检索它。你想去掉“action”属性:

<form method="POST">
...
</form>

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

关于python - Flask-login 不重定向到上一页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20766291/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com