I have a very simple python program using Flask shown below. It handles a login with a popup and logout. The problem is that the url in the browser is not updated by the redirect(url_for()) call.
@app.route('/')
def index():
if not 'username' in session:
# contains a button showing a login popup form with action set to '/login'
return render_template('welcome.html')
else:
# contains a logout button with a href to '/logout'
return render_template('webapp.html')
@app.route('/login', methods=['POST'])
def login():
session['username'] = request.form['username']
return redirect(url_for('index'))
@app.route('/logout')
def logout():
session.pop('username', None)
return redirect(url_for('index'))
When accessing '/' the welcome page is shown. When I click on the button, the login popup is shown and its form action redirects to '/login'. This works and the login() function is called and executed. The redirect as well, but the browser doesn't update the displayed url.
So the webapp page is shown with the /logon url. When I click reload I get an error because it tries to reload /logon while it should reload '/' where it has been redirected.
The same happens with /logout. When the webapp page is shown and I click the logout button, the /logout page is loaded which executes the logout() function and redirects to index. But the url is left to logout.
If I then reload the page, it succeeds because /logout accept the GET method and then the url is updated to / as it should have been in the first place.
I have the impression it is a jQuery mobile issue, but can't find out the problem. From the python and Flask point of view it matches all login examples I could find.
Flask class has a redirect() function. When called, it returns a response object and redirects the user to another target location with specified status code. location parameter is the URL where response should be redirected.
url_for in Flask is used for creating a URL to prevent the overhead of having to change URLs throughout an application (including in templates). Without url_for , if there is a change in the root URL of your app then you have to change it in every page where the link is present.
url_for() Another method you can use when performing redirects in Flask is the url_for() function. The way that url_for() works is instead of redirecting based on the string representation of a route, you provide the function name of the route you want to redirect to.
Finally solved it after finishing writing the question.
The problem is caused by jQuery mobile and the missing data-url attribute.
By adding the data-url attribute in the page div the url in the browser is updated and everything works fine.
<div data-role="page" id="welcome" data-url="{{ url_for('index') }}">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With