HTML 原文 · 完整 Markdown · 纯文本 · 分段目录 · ← 上一段 · 下一段 →

04-把依赖注入和 REST 约定结合起来,路由会干净很多

第 9 / 13 段:路径参数命名统一,会直接影响依赖复用

FastAPI 工程化实践 · 发布 2026-03-28 · 更新 2026-11-11 · 标签:FastAPI、Dependency Injection、REST

路径参数命名统一,会直接影响依赖复用(续)

# 基础依赖:校验 profile 是否存在
async def valid_profile(profile_id: int) -> Profile:
    profile = await profile_service.get(profile_id)
    if not profile:
        raise HTTPException(status_code=404, detail="Profile not found")
    return profile

# 扩展依赖:在 profile 存在的基础上,校验是否为创作者
async def valid_creator(profile: Profile = Depends(valid_profile)) -> Profile:
    if not profile.is_creator:
        raise HTTPException(status_code=403, detail="Not a creator")
    return profile

# 两个路由复用同一个 profile_id 参数名,依赖链自然串联
@router.get("/profiles/{profile_id}")
async def get_profile(profile: Profile = Depends(valid_profile)):
    return profile

@router.get("/creators/{profile_id}/posts")
async def get_creator_posts(creator: Profile = Depends(valid_creator)):
    return await posts_service.list_by_author(creator.id)

如果 /creators/ 路径的参数名写成了 creator_id,valid_profile 就没法直接复用了,因为它期望的参数名是 profile_id。这不是为了形式一致,而是为了让依赖链更自然。