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
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"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"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:
python
@app.route("/forbidden")
def forbidden():
return "No access", 403python
@app.route("/forbidden")
def forbidden():
return "No access", 403Or use abort()abort():
python
from flask import abort
@app.route("/admin")
def admin():
abort(403)python
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
