How to redirect a route to another in Flask app

How to redirect a route to another in Flask?

Python and Flask have the rich set of libraries and Classes which offer variety of tasks. You need not do lots code in Flask. Let’s come to the topic.

Finest example of redirecting route/web page is, when user login successfully , it is wise to redirect the login route to ‘chat room’, on a chat app. To do this you need to import the following packages.

from flask import redirect, url_for, request

After that you can use the redirect and url_for functions with return statement as follows

app.route(‘/login’, methods=[‘POST’, ‘GET’])
def login():
form = LoginForm()

if form.validate_on_submit():
user = User.query.filter_by(
if user:
if check_password_hash(user.password,
return redirect(url_for(‘chatroom’))
return ‘Invalid user name’

return render_template(‘signin.html’, form=form)

In our Chat example if the user login then the route will be redirected to ‘Chatroom’ route, which is the chatroom page for our app.

Published by


A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.