How To Redirect To Another Page In Python Flask

When working with web applications, it is a common requirement to redirect users from one page to another based on certain conditions. This tutorial will guide you on how to redirect to another page in a Flask web application.

Flask is a popular Python micro-framework for developing web applications. We will create a simple Flask application, and use the redirect() function from the flask module to redirect users from one route to another.

Step 1: Installation and Setup

First, make sure you have Python installed on your machine. Next, install Flask using pip:

Create a new Python file named app.py and import the necessary packages.

Then, create an instance of the Flask class and some basic routes:

To run the application, add the following code at the end of the file:

Step 2: Creating Routes to be Redirected

Now, let’s create some simple routes to demonstrate the redirection process. We will create two routes, /user/<username> and /admin, where the username is a variable. Based on the username, we will either redirect users to the admin page or the user page.

Add the following routes to your app.py file:

Step 3: Redirecting to Another Page

We will add another route, /login/<username>, that will act as a login mechanism. If the username entered is “admin”, the user will be redirected to the admin page. Otherwise, they will be redirected to the user page with their username.

To create the route and implement the redirection, add the following code to your app.py file:

In the code above, we are using the redirect() function from the flask module to redirect the user. The url_for() function is used to build the URL for the given route (either ‘admin’ or ‘user’).

Step 4: Testing the Redirection

Now, run your Flask application using the command:

Access your application at the following URLs:

  1. http://127.0.0.1:5000/login/admin: This URL should redirect you to the admin page.
  2. http://127.0.0.1:5000/login/johndoe: This URL should redirect you to the user page with the username “johndoe”.

Full Code

Here’s the complete code for the Flask application, including the redirect example.

Conclusion

In this tutorial, we have learned how to redirect users to another page in a Flask web application using the redirect() function. Redirection is an essential functionality in web applications, and knowing how to implement it will improve your web development skills.