关于 python-fastapi-patterns
面向 Python FastAPI 开发者的模式指南,涵盖项目组织、数据校验、依赖注入、异步处理、错误、配置、中间件与测试。
主要功能
- 01组织路由与服务层
- 02使用 Pydantic 校验数据
- 03注入共享依赖
- 04处理异步 I/O
- 05管理错误与配置
- 06使用 pytest 和 AsyncClient 测试
适用场景
- 01规划 FastAPI 应用结构
- 02创建经过校验的 API 端点
- 03测试异步 HTTP 路由
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ autohandai/ community-skills --skill python-fastapi-patterns安装后在 Claude Code 中输入/python-fastapi-patterns确认已加载。
详细介绍
Python FastAPI 模式
项目结构
src/
├── main.py # App entry point
├── config.py # Settings management
├── dependencies.py # Shared dependencies
├── models/ # Pydantic models
├── routes/ # API endpoints
├── services/ # Business logic
├── repositories/ # Data access
└── utils/ # Helpers
基本设置
# main.py
from fastapi import FastAPI
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup
await init_db()
yield
# Shutdown
await close_db()
app = FastAPI(
title="My API",
version="1.0.0",
lifespan=lifespan,
)
Pydantic 模型
from pydantic import BaseModel, Field, EmailStr
from datetime import datetime
from typing import Optional
class UserBase(BaseModel):
email: EmailStr
name: str = Field(min_length=2, max_length=100)
class UserCreate(UserBase):
password: str = Field(min_length=8)
class UserResponse(UserBase):
id: int
created_at: datetime
model_config = {"from_attributes": True}
class UserUpdate(BaseModel):
email: Optional[EmailStr] = None
name: Optional[str] = Field(None, min_length=2, max_length=100)
路由组织
# routes/users.py
from fastapi import APIRouter, Depends, HTTPException, status
from typing import Annotated
router = APIRouter(prefix="/users", tags=["users"])
@router.get("/", response_model=list[UserResponse])
async def list_users(
skip: int = 0,
limit: int = Query(20, le=100),
db: Session = Depends(get_db),
):
return await user_service.get_all(db, skip=skip, limit=limit)
@router.get("/{user_id}", response_model=UserResponse)
async def get_user(
user_id: int,
db: Session = Depends(get_db),
):
user = await user_service.get_by_id(db, user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
@router.post("/", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
async def create_user(
user_in: UserCreate,
db: Session = Depends(get_db),
):
return await user_service.create(db, user_in)
依赖注入
# dependencies.py
from fastapi import Depends, HTTPException, Security
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
security = HTTPBearer()
async def get_db():
db = SessionLocal()
try:
yield db
finally:
await db.close()
async def get_current_user(
credentials: HTTPAuthorizationCredentials = Security(security),
db: Session = Depends(get_db),
) -> User:
token = credentials.credentials
payload = decode_token(token)
if not payload:
raise HTTPException(status_code=401, detail="Invalid token")
user = await user_service.get_by_id(db, payload["sub"])
if not user:
raise HTTPException(status_code=401, detail="User not found")
return user
# Type alias for cleaner signatures
CurrentUser = Annotated[User, Depends(get_current_user)]
异步模式
import asyncio
from httpx import AsyncClient
# Parallel requests
async def fetch_all_data(user_id: int):
async with AsyncClient() as client:
tasks = [
client.get(f"/api/user/{user_id}"),
client.get(f"/api/user/{user_id}/posts"),
client.get(f"/api/user/{user_id}/stats"),
]
results = await asyncio.gather(*tasks)
return {
"user": results[0].json(),
"posts": results[1].json(),
"stats": results[2].json(),
}
# Background tasks
from fastapi import BackgroundTasks
@router.post("/notify")
async def send_notification(
email: str,
background_tasks: BackgroundTasks,
):
background_tasks.add_task(send_email, email)
return {"message": "Notification queued"}
错误处理
from fastapi import Request
from fastapi.responses import JSONResponse
class AppException(Exception):
def __init__(self, code: str, message: str, status_code: int = 400):
self.code = code
self.message = message
self.status_code = status_code
@app.exception_handler(AppException)
async def app_exception_handler(request: Request, exc: AppException):
return JSONResponse(
status_code=exc.status_code,
content={
"success": False,
"error": {"code": exc.code, "message": exc.message}
},
)
@app.exception_handler(Exception)
async def generic_exception_handler(request: Request, exc: Exception):
return JSONResponse(
status_code=500,
content={
"success": False,
"error": {"code": "INTERNAL_ERROR", "message": "Something went wrong"}
},
)
设置管理
# config.py
from pydantic_settings import BaseSettings
from functools import lru_cache
class Settings(BaseSettings):
app_name: str = "My API"
debug: bool = False
database_url: str
secret_key: str
model_config = {"env_file": ".env"}
@lru_cache
def get_settings() -> Settings:
return Settings()
中间件
from fastapi import Request
from time import time
import logging
logger = logging.getLogger(__name__)
@app.middleware("http")
async def log_requests(request: Request, call_next):
start = time()
response = await call_next(request)
duration = time() - start
logger.info(
f"{request.method} {request.url.path} "
f"status={response.status_code} duration={duration:.3f}s"
)
return response
测试
import pytest
from httpx import AsyncClient
from main import app
@pytest.fixture
async def client():
async with AsyncClient(app=app, base_url="http://test") as ac:
yield ac
@pytest.mark.asyncio
async def test_create_user(client: AsyncClient):
response = await client.post(
"/users/",
json={"email": "[email protected]", "name": "Test", "password": "password123"}
)
assert response.status_code == 201
assert response.json()["email"] == "[email protected]"
最佳实践
- 在所有地方使用类型提示,以便自动生成文档
- 在边界处进行验证,使用 Pydantic 模型
- 注入依赖项,提高可测试性
- 一致地处理错误,使用自定义异常
- 对 I/O 操作使用 async/await
- 保持路由精简——将业务逻辑放在服务中
- 使用 OpenAPI 注解编写文档
评论
支持 Markdown