Redirect is also a function provided by the flask. It is called redirect()  function. When this function is called, it returns a response object and also redirects the user to another location with the specific code.

The syntax of the redirect function is given below:

Flask.redirect(location, status code, response)

Here the first parameter is the location that is referred to as a target place where the user is going to be redirected.

The second parameter is the status code. It is sent to the header of the browser. The default code is 302, which stands for “found.” And the third one is the response, and it is used to instantiate the response.

We can understand this with the help of an example.

First of all, we have to create three pages.

  • Homepage=home3.html
  • Login page =login3.html
  • Python script=redirect.py

Both html file must be saved in the template folder that we made earlier  C:\Users\Erik_Akash\Documents\flask_app\templates and .py file saved to the C:\Users\Erik_Akash\Documents\flask_app folder.

Home3.html

login3.html

redirect.py

Run the redirect.py file, and the output is given below.

Now click on the login.

Flask Redirect and Errors

After clicking on the login button, a html form will appear. Fill this form and click on the Submit button.

Flask Redirect and Errors2

If the user enters the wrong details like an incorrect email id or password, then the page is going to redirect to the same page again and again until the user enters the correct details.

Example:

If the user enters an incorrect password, then it redirects the login page back again, and it will show notification, i.e., You have entered incorrect Email or password.

Flask Redirect and Errors3

When the correct key is entered, the output is.

Flask Redirect and Errors4

Abort function is a function of the flask. It is used in particular scenarios, in which some kind of errors occurred from the client-side in the request. It also provides a plain blank white error page for the user with basic information about the error.

Syntax of abort()  function.

Flask.abort(code)

Some of the most common error codes depend on the particular errors are as follows.

  • 400
Flask Redirect and Errors5
  • 401
Flask Redirect and Errors6
  • 403]
Flask Redirect and Errors7
  • 404
Flask Redirect and Errors8
  • 406 
Flask Redirect and Errors9
  • 415
Flask Redirect and Errors10

We can understand the working of the abort() function with the help of an example.

Note:- In this example, we use both the html templates and the same files that we used in the example of redirect() function, so we don’t have to create new files.

Abort1.py

Output

Click on the login.

Flask Redirect and Errors11

Fill the correct Email because the code has validation. Click on the Submit button to see how abort() function works.

Flask Redirect and Errors12
Flask Redirect and Errors13

Pin It on Pinterest

Share This