Open In App

Python Flask – Redirect and Errors

Last Updated : 07 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

We’ll discuss redirects and errors with Python Flask in this article. A redirect is used in the Flask class to send the user to a particular URL with the status code. conversely, this status code additionally identifies the issue. When we access a website, our browser sends a request to the server, and the server replies with what is known as the HTTP status code, which is a three-digit number, The different reasons for errors are:

  • Unauthorized access or poor request.
  • Unsupported media file types.
  • Overload of the backend server.
  • Internal hardware/connection error.

Syntax of Redirect

flask.redirect(location,code=302)

Parameters:

  • location(str): the location which URL directs to.
  • code(int): The status code for Redirect.
  • Code: The default code is 302 which means that the move is only temporary.

Return: The response object and redirects the user to another target location with the specified code.

The different  types of HTTP codes are:

Code

Status

300 Multiple_choices
301 Moved_permanently
302 Found
303 See_other
304 Not_modified
305 Use_proxy
306 Reserved
307 Temporary_redirect

Import the redirect attribute

We can redirect the URL using Flask by importing redirect. Let’s see how to import redirects from Flask

Python3




from flask import redirect


Example:

Let’s take a simple example to redirect the URL using a flask named app.py.

Python3




# importing redirect
from flask import Flask, redirect, url_for, render_template, request
  
# Initialize the flask application
app = Flask(__name__)
  
# It will load the form template which 
# is in login.html
@app.route('/')
def index():
    return render_template("login.html")
  
  
@app.route('/success')
def success():
    return "logged in successfully"
  
# loggnig to the form with method POST or GET
@app.route("/login", methods=["POST", "GET"])
def login():
    
    # if the method is POST and Username is admin then
    # it will redirects to success url.
    if request.method == "POST" and request.form["username"] == "admin":
        return redirect(url_for("success"))
  
    # if the method is GET or username is not admin,
    # then it redirects to index method.
    return redirect(url_for('index'))
  
  
if __name__ == '__main__':
    app.run(debug=True)


login.html

Create a folder named templates. In the templates, creates a templates/login.html file. On this page, we will take input from the user of its username.

HTML




<!DOCTYPE html>
<html lang="en">
   <body>
      <form method="POST", action="\login">
         Username: <input  name=username type=text></input><br>
         <button type="submit">Login</button>
      </form>
   </body>
</html>


Now we will deploy our code.

python app.py

Output:

 

Case 1: If the Username is admin and the method is POST then it will redirect to the success URL  and display logged in successfully.

 

 

Case 2: In the other case, if the Username is something like xyz or anything then it will redirect to the index method i.e., it will load the form again until the username is admin.

 

Flasks Errors

If there is an error in the address or if there is no such URL then Flask has an abort() function used to exit with an error code.

Syntax of abort() method

Syntax: abort(code, message)

  • code: int, The code parameter takes any of the following values
  • message: str, create your custom message Error.

The different types of errors we can abort in the application in your Flask. 

Code

Error

400 Bad request
401 Unauthenticated
403 Forbidden
404 Not Found
406 Not Acceptable
415 Unsupported Media Type
429 Too Many Requests

Example to demonstrate abort

In this example, if the username starts with a number then an error code message will through, else on success “Good username” will be printed.

Example 1:

Python3




# importing abort
from flask import Flask, abort
  
# Initialize the flask application
app = Flask(__name__)
  
  
@app.route('/<uname>')
def index(uname):
    if uname[0].isdigit():
        abort(400)
    return '<h1>Good Username</h1>'
  
  
if __name__ == '__main__':
    app.run()


Output:

Case 1: If the username doesn’t start with a number.

 

Case 2: If the username starts with a number.

Flask Redirect and Errors

 

Example 2:

In the above Python code, the status code to the abort() is 400, so it raises a Bad Request Error. Let’s try to change the code to 403. If the username starts with a number then it raises a Forbidden Error.

Python3




# importing abort
from flask import Flask, abort
  
# Initialize the flask application
app = Flask(__name__)
  
  
@app.route('/<uname>')
def index(uname):
    if uname[0].isdigit():
        abort(403)
    return '<h1>Good Username</h1>'
  
  
if __name__ == '__main__':
    app.run()


Output:

Flask Redirect and Errors

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads