第 2 章:路由与 URL 规则
一个 URL 背后是"规则 + 转换器 + 端点名"。搞懂这三样,路由就不再是玄学。
学习目标
- 会写带参数的路由,并选对转换器
- 明白尾斜杠为什么会导致 308 跳转
- 坚持用
url_for,而不是手拼 URL - 知道"看起来该匹配"却 404 的几种原因
2.1 三种写法
python
@app.route("/about") # 最基础
def about(): ...
@app.get("/items") # Flask 2.0+ 快捷
def list_items(): ...
@app.route("/login", methods=["GET", "POST"]) # 一个视图接两种方法
def login():
if request.method == "POST":
...同一个 URL 允许注册多个方法,但不要注册两个同 URL 同方法的视图——后者不会报错,而是静默覆盖。
2.2 路径参数与转换器
python
@app.get("/user/<int:user_id>") # 只接受整数
@app.get("/file/<path:filepath>") # 接受带 / 的路径
@app.get("/post/<slug>") # 默认 string,不含 /
@app.get("/session/<uuid:token>") # UUID 格式校验| 转换器 | 接受什么 | 典型用途 |
|---|---|---|
string(默认) | 任意文本,不含斜杠 | 用户名、slug |
int | 整数,负号也接受 | ID、页码 |
float | 浮点数 | 坐标、阈值 |
path | 含斜杠的路径 | 文件路径、多级 slug |
uuid | 标准 UUID 字符串 | 分享链接、幂等键 |
any(a,b) | 枚举里的一个 | /status/<any(open,closed):s> |
一个细节:int 匹配失败时返回 404,不会进视图。所以视图里不必再防 /user/abc。
自定义转换器(需要正则约束时):
python
from werkzeug.routing import BaseConverter
class SlugConverter(BaseConverter):
regex = r"[a-z0-9]+(?:-[a-z0-9]+)*"
app.url_map.converters["slug"] = SlugConverter
@app.get("/p/<slug:name>")
def post(name): ...2.3 尾斜杠:308 从哪来
python
@app.route("/docs") # 定义时不带斜杠此时访问 /docs/ 会得到 308 永久重定向到 /docs(Werkzeug 行为)。反过来定义 /docs/,访问 /docs 也会 308 跳到带斜杠的版本。
这是正常行为,不是 bug,但在 API 里很坑:
- 某些客户端不跟随 308,直接报错;
- POST 请求遇到 308 可能丢 body(取决于客户端实现)。
建议:API 路由统一不带尾斜杠;页面路由统一带。别混着来。
要关掉这个行为:
python
@app.route("/docs", strict_slashes=False)2.4 url_for:为什么不能手拼
python
from flask import url_for
url_for("user_profile", user_id=42) # → /user/42
url_for("static", filename="logo.png") # → /static/logo.png
url_for("index", _external=True) # → http://127.0.0.1:5000/三个理由:
- 重构安全:改了 URL 规则,模板和跳转自动跟着变;
- 蓝图前缀自动带:蓝图里的视图用
url_for("admin.users")就带上前缀(第 6 章); - 能带查询参数:
url_for("search", q="flask", page=2)→/search?q=flask&page=2。
模板里直接可用:
html
<a href="{{ url_for('user_profile', user_id=user.id) }}">{{ user.name }}</a>2.5 匹配顺序:谁先命中
一条实用排查法:视图没按预期执行时,先 print(app.url_map),看真实注册的规则列表和端点名。
2.6 404 与错误处理的入口
python
@app.errorhandler(404)
def not_found(e):
if request.path.startswith("/api/"):
return {"error": "not_found", "path": request.path}, 404
return render_template("404.html"), 404要点:错误处理要区分 API 与页面。API 返回 JSON,页面返回模板,混在一起会让前端解析失败。
2.7 路由设计的三条经验
| 经验 | 说明 |
|---|---|
| 名词复数 | /orders 而不是 /getOrders,REST 风格更稳 |
| 动作用方法表达 | DELETE /orders/42 比 /orders/delete?id=42 好 |
| 别在 URL 里放业务逻辑 | 参数进路径或查询串,别拼成 /getOrderById/42 |
2.8 四个常见 404 原因
| 现象 | 原因 |
|---|---|
| 路径参数带斜杠没匹配 | 用了默认 string 转换器,改用 path |
| 明明注册了却 404 | 蓝图注册时 url_prefix 与预期不一致 |
| 只匹配了 GET | 忘了写 methods=["POST"] |
| 大小写不同 | Flask 路由默认区分大小写(strict_slashes 管斜杠,不管大小写) |
本章小结
| 要点 | 说明 |
|---|---|
| 写法 | @app.route、@app.get、methods=[...] |
| 转换器 | string / int / float / path / uuid / any,可自定义正则 |
| 尾斜杠 | 不一致会 308 跳转;API 统一不带,页面统一带 |
| url_for | 反向生成,重构安全、自动带蓝图前缀 |
| 匹配优先级 | 静态段 > 动态 > 兜底,与注册顺序无关 |
| 排查 | app.url_map 打印真实规则 |
| 错误 | 404 处理要区分 API 与页面 |
下一章
请求与响应:数据从哪来、怎么取、返回什么形态,以及请求钩子该放在哪。