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.