from datetime import datetime, timezone
from typing import Annotated
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
Title = Annotated[str, Field(min_length=1, max_length=160)]
Slug = Annotated[str, Field(min_length=1, max_length=100, pattern=r"^[a-z0-9]+(?:-[a-z0-9]+)*$")]
Text = Annotated[str, Field(min_length=1, max_length=8000)]
CategoryId = Annotated[int, Field(gt=0)]
class CategoryBase(BaseModel):
name: str
slug: str
class CategoryResponse(CategoryBase):
id: int
model_config = ConfigDict(from_attributes=True)
class PostBase(BaseModel):
title: Title
slug: Slug
summary: str | None = None
content: Text
category_id: CategoryId
class PostCreate(PostBase):
model_config = ConfigDict(extra="forbid")
class PostUpdate(BaseModel):
model_config = ConfigDict(extra="forbid")
title: Title | None = None
slug: Slug | None = None
summary: str | None = None
content: Text | None = None
category_id: CategoryId | None = None
@model_validator(mode="after")
def reject_null_for_required_columns(self):
if any(getattr(self, field) is None for field in self.model_fields_set - {"summary"}):
raise ValueError("Only summary can be cleared with null")
return self
class PostResponse(PostBase):
id: int
created_at: datetime
updated_at: datetime
category: CategoryResponse
model_config = ConfigDict(from_attributes=True)
@field_validator("created_at", "updated_at")
@classmethod
def serialize_sqlite_utc(cls, value: datetime) -> datetime:
# Our specific model stores only UTC values in these two columns.
if value.tzinfo is None:
return value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc)
本例需在 CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0
入口文件:projects/fastapi-notebook-lab/schemas.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
schemas.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联3章) · 含当前章节或实例 · mbskycom202611a505.zip
课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a182.zip