0
0
Flaskframework~5 mins

Redirect and abort functions in Flask

Choose your learning style9 modes available
Introduction

Redirect and abort help control what the user sees next in a web app. Redirect sends users to another page, while abort stops the request with an error.

When you want to send a user to a different page after a form submission.
When a user tries to access a page they shouldn't see, and you want to show an error.
When a resource is not found and you want to show a 404 error.
When you want to guide users to login before accessing certain pages.
When you want to stop processing and return an error code quickly.
Syntax
Flask
from flask import redirect, abort

# Redirect usage
return redirect('/target-url')

# Abort usage
abort(404)  # stops and returns 404 error page

redirect sends the user to a new URL.

abort stops the request and shows an error code page.

Examples
Sends the user to the home page.
Flask
return redirect('/')
Sends the user to the login page.
Flask
return redirect('/login')
Stops the request and shows a 403 Forbidden error.
Flask
abort(403)
Stops the request and shows a 404 Not Found error.
Flask
abort(404)
Sample Program

This Flask app shows how to use redirect to send users to login if they are not logged in. It also uses abort to show a 404 error if an item is not found.

Flask
from flask import Flask, redirect, abort

app = Flask(__name__)

@app.route('/')
def home():
    return 'Welcome to the home page!'

@app.route('/secret')
def secret():
    # Only allow access if some condition is met
    user_logged_in = False
    if not user_logged_in:
        return redirect('/login')
    return 'Secret content here.'

@app.route('/login')
def login():
    return 'Please log in to continue.'

@app.route('/item/<int:item_id>')
def get_item(item_id):
    items = {1: 'Apple', 2: 'Banana'}
    if item_id not in items:
        abort(404)
    return f'Item: {items[item_id]}'

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

Use redirect to guide users smoothly between pages.

Use abort to stop processing and show error pages quickly.

You can customize error pages by creating error handlers in Flask.

Summary

redirect sends users to a new URL.

abort stops the request and shows an error code.

Both help control user flow and error handling in web apps.