Redirects and Errors
Redirects and errors are part of normal web flow.
flowchart TD
A["@app.route('/dir/')"] --> B["GET /dir/"]
B --> C["200"]
A --> D["GET /dir"]
D --> E["308 redirect to /dir/"]
E --> F["the browser follows -- it works, at the cost of a round trip"]
G["@app.route('/file')"] --> H["GET /file"]
H --> I["200"]
G --> J["GET /file/"]
J --> K["404 -- no redirect, no forgiveness"]
Redirects
Section titled “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"Why redirect after POST?
Section titled “Why redirect after POST?”The PRG pattern (Post/Redirect/Get) prevents form re-submission if the user refreshes.
Errors
Section titled “Errors”You can return an error status code directly:
@app.route("/forbidden")
def forbidden():
return "No access", 403Or use abort():
from flask import abort
@app.route("/admin")
def admin():
abort(403)abort() raises an HTTP exception that Flask turns into a proper response.
Common HTTP status codes
Section titled “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
Section titled “🧪 Try It Yourself”Exercise 1 – Create a Flask App
Section titled “Exercise 1 – Create a Flask App”Exercise 2 – Dynamic Route
Section titled “Exercise 2 – Dynamic Route”Exercise 3 – Return JSON
Section titled “Exercise 3 – Return JSON”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading