Flask 3 cheatsheet
Flask 3: Routes and requests
10 common Flask 3 tasks.
Capture part of the URL
Convert the value to an integer with a converter.
@app.get("/users/<int:user_id>")
def show_user(user_id):
return f"User {user_id}"
Handle several methods
Accept GET and POST on one route.
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
...
return render_template("login.html")
Return JSON
Return a dict or list and Flask converts it to JSON, with a status code.
@app.post("/api/users")
def create_user():
return {"id": 1, "name": "Ada"}, 201
Redirect to another route
Send the user to another endpoint by name.
return redirect(url_for("index"))
Customize an error page
Return a custom response for 404 errors.
@app.errorhandler(404)
def not_found(error):
return render_template("404.html"), 404
Run code before every request
Run a function before each request, for example to load the current user.
@app.before_request
def load_user():
g.user = get_user(session.get("user_id"))