我看到了很多与此相关的问题,但无法解决我的问题。我有一个 Flask 应用程序,带有 Flask-login 用于会话管理。而且,当我尝试在不登录的情况下查看页面时,我会被重定向到以下形式的链接/login/?next=%2Fsettings%2F
问题是,据我所知,“下一个”参数包含我实际需要的网站部分,但是当向登录表单提交请求时,它是通过POST
,所以这个参数不再可供我重定向到。
我尝试使用Request.path
from Request http://flask.pocoo.org/docs/api/#flask.Request.path%20Request(和网址)但两者都只返回/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('/')
Thanks
request.path http://flask.pocoo.org/docs/api/?highlight=request.path#flask.Request.path不是您要找的。它返回 URL 的实际路径。所以,如果您的网址是/a/?b=c
, then request.path
回报/a
, not c
正如你所期待的。
The next
参数位于?
在 URL 中,因此它是“查询字符串”的一部分。 Flask 已经为您解析了查询字符串中的项目,您可以使用以下方法检索这些值request.args http://flask.pocoo.org/docs/api/#flask.Request.args。如果您向该 URL 发送了请求/a/?b=c
并做了request.args.get('b')
,你会收到"c"
.
所以,你想使用request.args.get('next')
。文档在示例中展示了它是如何工作的 https://flask-login.readthedocs.org/en/latest/#how-it-works.
另一件需要记住的事情是,当您在 HTML 中创建登录表单时,您不想设置“action”属性。所以,不要这样做..
<form method="POST" action="/login">
...
</form>
这将导致 POST 请求被发送到/login
, not /login/?next=%2Fsettings%2F
,意味着你的next
参数不会成为查询字符串的一部分,因此您将无法检索它。您想省略“action”属性:
<form method="POST">
...
</form>
这将导致表单被发布到当前 URL(应该是/login/?next=%2Fsettings%2f
).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)