Python Flask - Redirect and Errors

Last Updated : 9 Mar, 2026

A redirect in Flask is used to send a user from one URL to another. When a redirect occurs, the server responds with an HTTP status code that instructs the browser to load a different location. Redirects are commonly used after form submissions, authentication checks or when a resource has moved.

Syntax

flask.redirect(location, code=302)

Parameters:

  • location (str): The URL where the user should be redirected.
  • code (int): The HTTP status code indicating the type of redirect.

Default Behavior: If no code is specified, Flask uses 302 (temporary redirect) by default.

Return: Returns a response object that redirects the user to the specified URL with the given HTTP status code.

HTTP Status Codes

HTTP status codes are three-digit numbers returned by the server to indicate how the request should be handled. The following codes are commonly associated with redirects:

CodeStatus
300Multiple Choices
301Moved Permanently
302Found (Temporary Redirect)
303See Other
304Not Modified
305Use Proxy
306Reserved
307Temporary Redirect

Importing the redirect Function

To perform URL redirection in Flask, we need to import the redirect function from the Flask module:

from flask import redirect

The redirect() function returns a response that instructs the browser to navigate to a different URL.

Example: Redirecting Based on Login Input

In this example, we create a simple Flask application that redirects users based on the username entered in a login form.

  • If the username is admin, the user is redirected to the success page.
  • Otherwise, the user is redirected back to the login page.

app.py

Python
from flask import Flask, redirect, url_for, render_template, request

# initialize the Flask application
app = Flask(__name__)

# route to display the login form
@app.route('/')
def index():
    return render_template("login.html")

# success page
@app.route('/success')
def success():
    return "logged in successfully"

# route to handle login request
@app.route("/login", methods=["POST", "GET"])
def login():

    # if username is admin and method is POST
    # redirect to success page
    if request.method == "POST" and request.form["username"] == "admin":
        return redirect(url_for("success"))

    # otherwise redirect back to login page
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug=True)

HTML Template (login.html)

Create a templates folder in the project directory and add the following file inside it. templates/login.html

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>

Run the Flask application using:

python app.py

Output

main page

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.

adding username as admin and click login
after clicking login button

Case 2: If the username is anything other than admin, the application redirects back to the login page, allowing the user to enter the username again.

entering username other than admin

url_for() Function

url_for() function in Flask is used to dynamically generate URLs for a specific function. It takes the function name as the first argument and builds the corresponding URL. This is useful when performing redirects because it avoids hardcoding URLs and makes the application easier to maintain.

Example: Here, the user(name) route checks whether the provided name is admin. If it matches, the request is redirected to the admin page; otherwise, it redirects to the guest page.

Python
from flask import Flask, redirect, url_for
app = Flask(__name__)

# Route for admin page
@app.route('/admin')
def hello_admin():
    return 'Hello Admin'

# Route for guest page
@app.route('/guest/<guest>')
def hello_guest(guest):
    return 'Hello %s as Guest' % guest

# Route that decides where to redirect
@app.route('/user/<name>')
def hello_user(name):

    # Redirect based on the username
    if name == 'admin':
        return redirect(url_for('hello_admin'))
    else:
        return redirect(url_for('hello_guest', guest=name))

if __name__ == '__main__':
    app.run(debug=True)

Output: When the URL is /user/admin, the application redirects to the admin page and displays:

When the URL is /user/Ayush, the application redirects to the guest page and displays:

The url_for() function ensures that URLs are generated dynamically, which helps keep routing flexible and prevents issues if route paths change later.

Flasks Errors

Flask provides the abort() function to stop request processing and return an HTTP error response. It is commonly used when a requested resource does not exist, the request is invalid, or access is not allowed.

Syntax of abort()

abort(code, message=None)

Parameters:

  • code (int): The HTTP status code that represents the type of error.
  • message (str, optional): A custom error message that can be returned with the response.

When abort() is called, Flask immediately stops the current request and returns the specified error code to the client.

HTTP Error Codes

The following HTTP status codes are commonly used when handling errors in Flask applications:

Code

Error

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

Example to Demonstrate abort()

Example 1: In this example, we check the username provided in the URL using Error Code 400. If username starts with a number, application raises an error using the abort() function. Otherwise, it returns a success message.

Python
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 does not start with a number, the page displays:

if username doesnt start with a number

Case 2: If the username starts with a number, Flask raises a 400 Bad Request error.

Flask Redirect and Errors
if username start with a number

Example 2: In this example, error code in abort() is changed to 403. If the username starts with a number, the application raises a Forbidden error instead.

Python
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: If the username starts with a number, Flask returns a 403 Forbidden error. Otherwise, page displays "Good Username".

Flask Redirect and Errors
when username start with a number
Comment