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(username=form.username.data).first()
if user:
if check_password_hash(user.password, form.password.data):
login_user(user, remember=form.remember.data)
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.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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.