怎么把多个 APIRouter 加到主应用?
先说出你的答案
定义边界、关键机制、一个反例;P8题再补容量、失败与验证。
查看完整题解
参考回答
直接回答
在各模块定义路由器,初始化主应用时调用 app.include_router。可在注册时再传前缀、标签或依赖。绑定前确认没有重复方法与路径。
讲清原理
最终路径由注册前缀与路由内路径组合。业务模块不需要导入主应用实例,也便于测试时单独组装。
例子与易错点
示例把订单与商品路由器分别挂载,测试客户端能按两个前缀获取不同结果。
from fastapi import APIRouter, FastAPI
from fastapi.testclient import TestClient
orders = APIRouter()
products = APIRouter()
@orders.get("/")
def order_index():
return {"resource": "orders"}
@products.get("/")
def product_index():
return {"resource": "products"}
app = FastAPI()
app.include_router(orders, prefix="/orders", tags=["orders"])
app.include_router(products, prefix="/products", tags=["products"])
with TestClient(app) as client:
assert client.get("/orders/").json() == {"resource": "orders"}
assert client.get("/products/").json() == {"resource": "products"}
print("both routers mounted")
和评分标准对照,你能独立回答到哪一步?
自评会安排下一次复习,不保存你的口述内容。
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。