除了基础的 Depends 外,FastAPI 的依赖注入支持高级模式:子依赖项、带参数的依赖项(基于类或通过工厂)、作用域资源(yield)、全局/路由器依赖项 和 依赖项覆盖用于测试 — 使其成为构造实际应用程序的多功能工具。
子依赖项(依赖树)
python
def get_token(authorization: str = Header()):
return parse(authorization)
def get_current_user(token: str = Depends(get_token)): # depends on another dependency
return decode(token)
def get_admin(user: User = Depends(get_current_user)): # depends on that, in turn
if not user.is_admin: raise HTTPException(403)
return user
# FastAPI resolves the whole chain, caching shared dependencies within a request
依赖项可以依赖于其他依赖项,形成 FastAPI 自动解析的树(并缓存每个请求中的共享依赖项,因此 get_token 即使被多个依赖项使用也只运行一次)。
class RateLimiter:
def __init__(self, calls: int): # configure the dependency
self.calls = calls
def __call__(self, request: Request): # callable → acts as a dependency
check_rate_limit(request, self.calls)
@app.get("/items", dependencies=[Depends(RateLimiter(calls=100))]) # configured per route
def items(): ...
带有 __call__ 的类是可配置的依赖项 — 你在使用时进行参数化(例如为不同的路由设置不同的速率限制)。
@app.get("/admin", dependencies=[Depends(verify_admin)]) # run for the effect (auth check)
def admin(): ... # don't need its return value
app = FastAPI(dependencies=[Depends(verify_api_key)]) # applies to EVERY route
router = APIRouter(dependencies=[Depends(get_current_user)]) # to all routes in a router
应用范围内或按路由器应用依赖项以满足跨层问题(身份验证、速率限制)。
app.dependency_overrides[get_db] = get_test_db # swap any dependency in tests
FastAPI 的依赖注入是其最强大的特性之一,这些高级模式正是让你优雅地构造真实复杂应用程序的关键。
理解它们是有价值的高级知识:子依赖项构建可重用的层(token → user → admin),具有自动解析和按请求缓存(避免冗余工作);参数化/基于类的依赖项创建可配置、可重用的组件(速率限制器、权限检查,每个路由具有不同的设置);依赖项作为副作用清晰地强制执行需求(身份验证),而不会使函数签名变得复杂;全局/路由器级依赖项将跨层关注点(身份验证、速率限制)应用于整组路由。
至关重要的是,依赖项覆盖使即使是复杂的依赖关系图也可以轻松测试。
掌握这些模式 — 组合依赖项、参数化它们、全局或按路由器作用域,以及在测试中覆盖它们 — 正是在非平凡的 FastAPI 应用程序中实现干净、DRY、可测试架构的关键,区分了能够充分利用框架 DI 系统的开发人员和仅使用基础 Depends 的开发人员。
这是构建结构良好、可维护、大规模 FastAPI 应用程序的重要主题。
一个包含详细解答的 IT 面试题库——从初级到高级。
捐赠