Flask-login not redirecting to previous page

て烟熏妆下的殇ゞ 提交于 2019-12-03 06:27:46

request.path is not what you're looking for. It returns the actual path of the URL. So, if your URL is /a/?b=c, then request.path returns /a, not c as you are expecting.

The next parameter is after the ? in the URL, thus it is part of the "query string". Flask has already parsed out items in the query string for you, and you can retrieve these values by using request.args. If you sent a request to the URL /a/?b=c and did request.args.get('b'), you would receive "c".

So, you want to use request.args.get('next'). The documentation shows how this works in an example.

Another thing to keep in mind is that when you are creating your login form in HTML, you don't want to set the "action" attribute. So, don't do this..

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

This will cause the POST request to be made to /login, not /login/?next=%2Fsettings%2F, meaning your next parameter will not be part of the query string, and thus you won't be able to retrieve it. You want to leave off the "action" attribute:

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

This will cause the form to be posted to the current URL (which should be /login/?next=%2Fsettings%2f).

You can use mongoengine sessions to pass 'next_url' parameter with flask session (from flask import session). In py file where you define your app and login_manager:

from flask.ext.mongoengine import MongoEngineSessionInterface
app.session_interface = MongoEngineSessionInterface(db)

@login_manager.unauthorized_handler
def unauthorized_callback():
    session['next_url'] = request.path
    return redirect('/login/')

and then in login view:

def login():
    # ... if success
    next_url = session.get('next_url', '/')
    session.clear()
    return redirect(next_url)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!