FastAPI 的依赖注入系统让你声明可重用的 dependencies(函数/类),FastAPI 调用这些 dependencies 并通过 Depends() 将其注入到你的 path operations 中。它用于共享逻辑,如数据库连接、认证和常见参数——保持代码 DRY 和可测试。
一个基础 dependency
fastapi Depends
():
{: skip, : limit}
():
params
声明 params = Depends(pagination) 告诉 FastAPI 调用 pagination(也从请求中解析它的参数)并将结果传递到你的函数中。该 dependency 可在许多端点间重用。
def get_db():
db = SessionLocal()
try:
yield db # provide the session to the endpoint
finally:
db.close() # cleanup runs AFTER the response — guaranteed
@app.get("/users")
def list_users(db = Depends(get_db)):
return db.query(User).all() # uses the injected, auto-closed session
一个 yield dependency 提供资源并在请求后运行清理 —— 是数据库连接的标准模式(先打开,后关闭,自动执行)。
def get_current_user(token: str = Depends(get_token)): # depends on another dependency
return decode(token)
@app.get("/me")
def me(user: User = Depends(get_current_user)): # auth via injection
return user
Dependencies 形成一棵树 —— FastAPI 解析整个链。这是认证通常的实现方式(一个 get_current_user dependency)。
@app.get("/items", dependencies=[Depends(verify_api_key)]) # run a dependency without using its return
def items(): ... # e.g. enforce auth as a side effect
依赖注入是 FastAPI 最强大和最重要的特性之一 —— 它是你在端点间干净地共享和重用逻辑的方式(数据库连接、认证、常见查询参数、权限检查),无需重复。
理解它至关重要,因为它支撑核心模式:yield dependency 是管理数据库连接的标准方式(每个请求后保证清理),而**get_current_user dependency** 是实现认证的习惯用法。
DI 还使代码高度可测试 —— 你可以在测试中用 mocks 覆盖 dependencies。
该系统的优雅之处(dependencies 从请求中解析它们自己的参数,可以依赖其他 dependencies 形成树,并与文档集成)使其成为构建真实应用的多功能工具,因此掌握 Depends 是构建良好组织、易于维护、可测试的 FastAPI 应用的关键。