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", 403Or 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 coffeeWas this page helpful?
Let us know how we did
