多用内置验证,不要把简单规则都写成手工校验
对比一下两种写法就知道差别有多大:
# 手工校验:散落在 service 层,容易遗漏
@router.post("/products")
async def create_product(data: dict):
if not data.get("name") or len(data["name"]) > 100:
raise HTTPException(400, "name is required and must be under 100 chars")
if data.get("price") is not None and data["price"] < 0:
raise HTTPException(400, "price must be non-negative")
if data.get("category") not in ("electronics", "clothing", "food"):
raise HTTPException(400, "invalid category")
...
# Pydantic 内置校验:在模型层一次解决
from enum import Enum
class Category(str, Enum):
electronics = "electronics"
clothing = "clothing"
food = "food"
class ProductCreate(BaseModel):
name: str = Field(min_length=1, max_length=100)
price: float = Field(ge=0)
category: Category
url: HttpUrl | None = None
@router.post("/products")
async def create_product(data: ProductCreate):
... # 走到这里时数据一定是合法的