Routing
Routing is used to bind URLs with view functions, determining which code handles user access to specific paths.
Basic Usage:
python
@app.route("/")
def index():
return "Index"
@app.get("/hello")
def hello():
return "Hello"
@app.route("/submit", methods=["POST"]) # Multiple methodsURL Parameters:
python
@app.get("/user/<username>")
def profile(username):
return f"User: {username}"
@app.get("/post/<int:post_id>")
def post_detail(post_id):
return f"Post #{post_id}"Building URLs:
python
from flask import url_for
url_for("index")
url_for("post_detail", post_id=123)Redirect:
python
from flask import redirect
return redirect(url_for("index"), code=302)Custom Converters: Used for regex or complex matching (advanced topic omitted).
Route Order: Matches in registration order, try to avoid overlapping/ambiguous paths.