Skip to content

Routing

路由用于将 URL 与视图函数绑定,决定用户访问路径时由哪段代码处理。

基础用法:

python
@app.route("/")
def index():
    return "Index"

@app.get("/hello")
def hello():
    return "Hello"

@app.route("/submit", methods=["POST"])  # 多方法

URL 参数:

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}"

构造 URL:

python
from flask import url_for
url_for("index")
url_for("post_detail", post_id=123)

重定向:

python
from flask import redirect
return redirect(url_for("index"), code=302)

自定义转换器:用于正则或复杂匹配(进阶主题略)。

路由顺序:按注册顺序匹配,尽量避免重叠/歧义路径。

本站内容仅供学习和研究使用。