Table of contents
1.
Introduction
2.
Redirect and Error Handling
2.1.
Syntax for Redirect in Flask
2.2.
Status Codes in Flask Redirect
3.
Example for Redirect and Error Handling
4.
Frequently Asked Questions
5.
Key Takeaways
Last Updated: Mar 27, 2024

Redirect and Error handling in Flask

Author Sneha Mallik
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Flask is a lightweight and small Python web framework that provides essential tools and capabilities for building online applications in Python. Since we can build a web application easily using only a single Python file, it allows the developers with more flexibility and is a more accessible framework for beginning developers.

In this blog, we will learn the concept of redirect and error handling in Flask and will also look upon the uses of redirect and error in the Flask web applications.

Redirect and Error Handling

​​The redirect() function in the Flask class redirects the user to a specified URL(Uniform Resource locator) with the provided status code.

An HTTP status code is the server's response to the browser's request. When we visit a website, our browser sends a request to the server, which the server responds to with a three-digit code called the HTTP status code. The error is also represented by this status code.

Syntax for Redirect in Flask

The redirect() function's syntax is listed below:

Flask.redirect(<location>, <status_code>, <response>)  

Syntax Parameter

Explanation

‘location’

The location parameter specifies the URL where the response should be redirected.

‘status_code’

This is the status code which is provided along with the server's response to the browser's header.

‘response’

It's the response instance that will be used in the project for future needs.

Status Codes in Flask Redirect

The following are the standardised status codes:

  • HTTP_300_MULTIPLE_CHOICES
  • HTTP_301_MOVED_PERMANENTLY
  • HTTP_302_FOUND
  • HTTP_303_SEE_OTHER
  • HTTP_304_NOT_MODIFIED
  • HTTP_305_USE_PROXY
  • HTTP_306_RESERVED
  • HTTP_307_TEMPORARY_REDIRECT

Note: Status Code - 302, which represents for 'found', is the default status code.

Example for Redirect and Error Handling

Consider the following scenario: Upon successful login, the user is redirected to the success page with the HTTP status code 302 (found); otherwise, the user is redirected to this page only.

login.py:

from flask import * 

# Initializing the Flask application
app = Flask(__name__)
@app.route('/') 
def home (): 
   return render_template("home.html") 
@app.route('/login') 
def login(): 
   return render_template("login.html"); 
@app.route('/validate', methods = ['POST']) 
def validate(): 
   if request.method == 'POST' and request.form['pass'] == 'ninja': 
       return redirect(url_for("success")) 
   return redirect(url_for("login")) 
@app.route('/success') 
def success(): 
   return "You have logged in successfully!" 
 if __name__ == '__main__': 
   app.run(debug = True)
You can also try this code with Online Python Compiler
Run Code

home.html:

<html> 
<head> 
<title>home</title> 
</head> 
<body> 
<h1>Welcome to Coding Ninjas</h1> 
<p>Example for redirect and error handling in Flask Application</p> 
<a href = "/login">Click here to login!</a><br> 
</html>

login.html:

<html> 
<head> 
   <title>login</title> 
</head> 
<body> 
   <form method = "post" action = "http://127.0.0.1:5000/validate"> 
       <table> 
           <tr><td>Email</td><td><input type = 'email' name = 'email'></td></tr> 
           <tr><td>Password</td><td><input type = 'password' name = 'pass'></td></tr> 
           <tr></tr>
           <tr><td><input type = "submit" value = "Submit"></td></tr> 
       </table> 
   </form> 
</body> 
</html>

 

The URL '/' in the above example contains a link to the home page, as shown in the image below.

The login page, as seen in the image below, encourages the user to input his or her email address and password, and the submit button takes the user to the URL /validate. 

If we enter any wrong password other than ‘ninja’ and click the ‘Submit’ button, the page gets redirected to the login page like below.

If the user's password is 'ninja', the user is redirected to the URL /success. In the image below, the URL http://127.0.0.1:5000/success (which is generated after a successful login) is displayed.

Want to learn about , PHP For Loop click here

Frequently Asked Questions

1. What do you mean by Flask abort() function?

Ans: The abort() function is used to handle scenarios where client-side failures are present in requests, such as bad requests, illegal or unauthorized access, and so on. The error code, on the other hand, must be mentioned as the cause of the error.

Syntax: 

Flask.abort(code)
You can also try this code with Online Python Compiler
Run Code

 

2. What are the different types of error?

Ans: Depending on the errors, we can specify the following error codes.

  • For the poor requests: 400
  • For the unauthorized access: 401
  • Forbidden: 403
  • Not Found: 404
  • Not acceptable: 406
  • Unsupported media file types: 415
  • Too many requests: 429

 

3. What is the purpose of redirects?

Ans: It is an important component of web applications and improves the application's efficiency.

Take Twitter, for example: if you are not already logged in, you will be sent to the log-in page when you visit the Twitter URL (www.twitter.com). The redirect feature comes into play here.

Similarly, after completing an online transaction, you will be forwarded to the confirmation page.

Another advantage of redirecting is that it facilitates URL shortening, such as https://bit.ly. You type a short URL here and are then redirect it to the original lengthy one.

 

4. How do we import the redirect attribute?

Ans: We import the redirect attribute with the following syntax:

from flask import redirect 
You can also try this code with Online Python Compiler
Run Code


5. Why is the abort() function used?

Ans: The abort() function in Flask is used for the special redirect cases of failure.

Syntax:

abort(<error_codes>)

We import the abort attribute with the following syntax:

from flask import abort 
You can also try this code with Online Python Compiler
Run Code

Key Takeaways

In this blog, we have learned the concepts of redirect and error handling in Flask. The redirect() function is available in the Flask class. When it is invoked, it returns a response object and redirects the user to a different target location with the provided status code. We also learned about abort() attributes in Flask.

Take a look at our Flask archives section and see many more interesting topics related to it. Apart from that, you can refer to our Guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc.

Credits: GIPHY

Happy Developing!

Live masterclass