Skip to content

Redirects and Errors

Redirects and errors are part of normal web flow.

Redirects

A redirect tells the client: β€œgo to a different URL.”

Common use cases:

  • after successful form submission (POST β†’ redirect β†’ GET)
  • redirecting legacy URLs
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"
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"

Why redirect after POST?

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

Errors

You can return an error status code directly:

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

Or use abort()abort():

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

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

Common HTTP status codes

  • 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

πŸ§ͺ Try It Yourself

Exercise 1 – Create a Flask App

Exercise 2 – Dynamic Route

Exercise 3 – Return JSON

If this helped you, consider buying me a coffee β˜•

Buy me a coffee

Was this page helpful?

Let us know how we did