Skip to content

Redirects and Errors

Redirects and errors are part of normal web flow.

diagram the trailing slash rule, which is not symmetric mermaid
Flask treats a rule ending in a slash as a directory and one without as a file, and the two behave differently when the request does not match. A directory rule forgives a missing slash with a redirect. A file rule does not forgive an extra one -- it returns 404. Both behaviours were measured.

A redirect tells the client: “go to a different URL.”

Common use cases:

  • after successful form submission (POST → redirect → GET)
  • redirecting legacy URLs
python
from flask import Flask, redirect, url_for
 
app = Flask(__name__)
 
 
@app.route("/old")
def old():
    return redirect(url_for("new"))
 
 
@app.route("/new")
def new():
    return "New page"

The PRG pattern (Post/Redirect/Get) prevents form re-submission if the user refreshes.

You can return an error status code directly:

python
@app.route("/forbidden")
def forbidden():
    return "No access", 403

Or use abort():

python
from flask import abort
 
@app.route("/admin")
def admin():
    abort(403)

abort() raises an HTTP exception that Flask turns into a proper response.

  • 400 Bad Request — invalid input
  • 401 Unauthorized — not logged in (auth missing)
  • 403 Forbidden — logged in but not allowed
  • 404 Not Found — route/resource doesn’t exist
  • 500 Internal Server Error — unhandled exception

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading