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’])
form = LoginForm()
user = User.query.filter_by(username=form.username.data).first()
if check_password_hash(user.password, form.password.data):
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.