用依赖项把前置逻辑分层
把这些检查拆成依赖项,让每一层只做一件事:
from fastapi import Depends, HTTPException
async def valid_post(post_id: int) -> Post:
# 第一层:资源存在性校验
post = await posts_service.get(post_id)
if not post:
raise HTTPException(status_code=404, detail="Post not found")
return post
async def owned_post(
post: Post = Depends(valid_post),
user: User = Depends(current_user),
) -> Post:
# 第二层:所有权校验
if post.author_id != user.id:
raise HTTPException(status_code=403, detail="Forbidden")
return post
async def editable_post(post: Post = Depends(owned_post)) -> Post:
# 第三层:业务前置条件校验
if post.status == "archived":
raise HTTPException(status_code=400, detail="Archived post cannot be updated")
return post
路由就会收敛成这样:
@router.patch("/posts/{post_id}")
async def update_post(payload: PostUpdate, post: Post = Depends(editable_post)):
return await posts_service.update(post.id, payload)
这组代码真正体现的是"前置条件逐层收敛":