返回专栏
专栏 ·

12.1 架构设计:基于 FastAPI + Asyncio + Pydantic 构建高性能异步微服务 API

作者: 九路 共 12 章 · 48 小节

欢迎来到 HelloWorld 技术社区(www.helloworld.net) 《Python 现代开发实战》第 12 章终极收官项目!

现在,我们将把前 11 章学到的全部工程规范、类型注解、Pydantic 校验、异步并发与生命周期管理串联起来,构建一个生产级的 HelloWorld 社区文章与打卡微服务。

from contextlib import asynccontextmanager
from collections.abc import AsyncIterator
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel, Field


class ArticleCreate(BaseModel):
    title: str = Field(min_length=3, max_length=80)
    author: str
    tags: list[str] = Field(default_factory=list)


class ArticleOut(ArticleCreate):
    id: int


# 使用现代 lifespan 上下文管理器替代已废弃的 @app.on_event("startup")
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    app.state.db: dict[int, ArticleOut] = {}
    app.state.seq = 0
    yield
    app.state.db.clear()


app = FastAPI(title="HelloWorld Community API", version="1.0.0", lifespan=lifespan)


@app.post("/api/v1/articles", response_model=ArticleOut, status_code=status.HTTP_201_CREATED)
async def create_article(payload: ArticleCreate) -> ArticleOut:
    app.state.seq += 1
    article = ArticleOut(id=app.state.seq, **payload.model_dump())
    app.state.db[article.id] = article
    return article


@app.get("/api/v1/articles/{article_id}", response_model=ArticleOut)
async def get_article(article_id: int) -> ArticleOut:
    if (article := app.state.db.get(article_id)) is None:
        raise HTTPException(status_code=404, detail="文章不存在")
    return article

💬 HelloWorld 社区实战打卡

运行上述 FastAPI 服务,访问自动生成的 /docs(Swagger UI)完成一次创建与查询测试,带 #Python专栏打卡 分享你的界面截图!