FastAPI实战:AI应用后端的首选框架
AI · 技术

FastAPI实战:AI应用后端的首选框架

FastAPI 完整学习文档

📅 更新时间:2026-06-21
🎯 适用版本:FastAPI 0.115+ / Python 3.12+
📦 基于:Pydantic v2 + SQLAlchemy 2.0 + asyncpg

目录

  1. 概述与核心优势
  2. 快速入门
  3. 核心概念详解
  4. Pydantic 数据模型
  5. 依赖注入系统
  6. 数据库集成
  7. 认证与授权
  8. 中间件与CORS
  9. 后台任务与WebSocket
  10. 项目结构最佳实践
  11. 测试策略
  12. 生产部署
  13. 性能优化
  14. 学习资源

1. 概述与核心优势

1.1 什么是 FastAPI?

FastAPI 是一个现代、高性能的 Python Web 框架,用于构建 API。它基于:

  • Starlette - Web 层(ASGI)
  • Pydantic - 数据层(验证和序列化)
  • Python 类型提示 - 自动生成文档

1.2 核心优势

特性 说明
🚀 高性能 与 Node.js、Go 性能相当,得益于 async 支持
📝 自动文档 Swagger UI (/docs) 和 ReDoc (/redoc) 零配置生成
✅ 自动验证 Pydantic 模型自动验证请求数据
💉 依赖注入 内置 DI 系统,代码更清晰、更易测试
⚡ 异步优先 原生 async/await 支持,无需第三方扩展
🔒 类型安全 完整的类型提示,IDE 支持优秀
📊 标准兼容 基于 OpenAPI 3.1 和 JSON Schema

1.3 谁在使用?

Microsoft、Uber、Netflix、Explosion AI、Klarna 等公司都在生产环境使用 FastAPI。


2. 快速入门

2.1 安装

# 创建虚拟环境
python -m venv venv
source venv/bin/activate  # Linux/Mac
# venv\Scripts\activate   # Windows

# 安装 FastAPI(包含所有依赖)
pip install "fastapi[standard]"

# 或者最小安装
pip install fastapi uvicorn

2.2 第一个 API

# main.py
from fastapi import FastAPI

app = FastAPI(
    title="我的第一个 API",
    description="学习 FastAPI 的示例项目",
    version="1.0.0"
)

@app.get("/")
async def root():
    return {"message": "Hello, World!"}

@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str | None = None):
    return {"item_id": item_id, "q": q}

2.3 运行服务

# 开发模式(自动重载)
fastapi dev main.py

# 生产模式
fastapi run main.py

# 或者使用 uvicorn
uvicorn main:app --reload --host 0.0.0.0 --port 8000

2.4 访问文档

  • Swagger UI: http://localhost:8000/docs
  • ReDoc: http://localhost:8000/redoc
  • OpenAPI JSON: http://localhost:8000/openapi.json

3. 核心概念详解

3.1 路径参数

from fastapi import FastAPI, Path

app = FastAPI()

# 基本路径参数
@app.get("/users/{user_id}")
async def read_user(user_id: int):
    return {"user_id": user_id}

# 带验证的路径参数
@app.get("/items/{item_id}")
async def read_item(
    item_id: int = Path(..., title="物品ID", ge=1, le=1000)
):
    return {"item_id": item_id}

3.2 查询参数

from fastapi import FastAPI, Query

app = FastAPI()

@app.get("/items/")
async def read_items(
    q: str | None = None,
    skip: int = Query(0, ge=0),
    limit: int = Query(10, ge=1, le=100)
):
    return {"q": q, "skip": skip, "limit": limit}

3.3 请求体

from fastapi import FastAPI
from pydantic import BaseModel, Field

class Item(BaseModel):
    name: str = Field(..., min_length=1, max_length=100)
    description: str | None = Field(None, max_length=500)
    price: float = Field(..., gt=0)
    tax: float | None = None

app = FastAPI()

@app.post("/items/", status_code=201)
async def create_item(item: Item):
    return item.dict()

3.4 async def vs def

# ✅ 使用 async def 处理 I/O 操作
@app.get("/async-example")
async def async_example():
    result = await some_async_operation()
    return result

# ✅ 使用 def 处理 CPU 密集型操作
@app.get("/sync-example")
def sync_example():
    result = cpu_intensive_task()  # FastAPI 自动在线程池运行
    return result

规则:

  • I/O 操作(数据库、HTTP 调用)→ async def
  • CPU 密集型操作 → def(FastAPI 自动在线程池运行)
  • 不确定 → 使用 async def

4. Pydantic 数据模型

4.1 Pydantic v2 基础

from pydantic import BaseModel, Field, ConfigDict
from datetime import datetime
from typing import Optional

class UserBase(BaseModel):
    """用户基础模型"""
    username: str = Field(..., min_length=3, max_length=50)
    email: str = Field(..., pattern=r'^[\w\.-]+@[\w\.-]+\.\w+$')
    full_name: str | None = Field(None, max_length=100)

class UserCreate(UserBase):
    """创建用户的请求模型"""
    password: str = Field(..., min_length=8)

class UserResponse(UserBase):
    """用户响应模型"""
    model_config = ConfigDict(from_attributes=True)
    
    id: int
    is_active: bool
    created_at: datetime

class UserUpdate(BaseModel):
    """更新用户的请求模型(所有字段可选)"""
    username: str | None = None
    email: str | None = None
    full_name: str | None = None

4.2 常用验证器

from pydantic import BaseModel, Field, field_validator

class Product(BaseModel):
    name: str = Field(..., min_length=1, max_length=200)
    price: float = Field(..., gt=0, description="价格必须大于0")
    quantity: int = Field(0, ge=0)
    tags: list[str] = []
    
    @field_validator('name')
    @classmethod
    def name_must_not_be_empty(cls, v):
        if not v.strip():
            raise ValueError('名称不能为空')
        return v.strip()
    
    @field_validator('price')
    @classmethod
    def price_must_be_reasonable(cls, v):
        if v > 1000000:
            raise ValueError('价格不能超过100万')
        return round(v, 2)

4.3 模型继承与组合

from pydantic import BaseModel
from datetime import datetime

# 基础模型
class TimestampMixin(BaseModel):
    created_at: datetime = None
    updated_at: datetime = None

# 继承
class Article(TimestampMixin):
    title: str
    content: str
    author_id: int

# 组合
class Author(BaseModel):
    name: str
    articles: list[Article] = []

4.4 Pydantic v2 vs v1 主要区别

特性 v1 v2
核心实现 Python Rust(5-50x 更快)
ORM 模式 orm_mode = True from_attributes = True
配置类 class Config: model_config = ConfigDict()
验证器 @validator @field_validator
导出方法 .dict() .model_dump()

5. 依赖注入系统

5.1 基础依赖注入

from fastapi import FastAPI, Depends, HTTPException

app = FastAPI()

# 定义依赖
async def get_db():
    db = DatabaseSession()
    try:
        yield db
    finally:
        db.close()

# 使用依赖
@app.get("/users/{user_id}")
async def read_user(
    user_id: int,
    db: DatabaseSession = Depends(get_db)
):
    user = db.get(User, user_id)
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return user

5.2 类作为依赖

from fastapi import FastAPI, Depends, Query

class PaginationParams:
    def __init__(
        self,
        skip: int = Query(0, ge=0),
        limit: int = Query(10, ge=1, le=100)
    ):
        self.skip = skip
        self.limit = limit

@app.get("/items/")
async def read_items(
    pagination: PaginationParams = Depends()
):
    return {"skip": pagination.skip, "limit": pagination.limit}

5.3 嵌套依赖

async def get_current_user(
    token: str = Depends(oauth2_scheme),
    db: Session = Depends(get_db)
) -> User:
    user = verify_token(token, db)
    if not user:
        raise HTTPException(status_code=401)
    return user

async def get_current_active_user(
    current_user: User = Depends(get_current_user)
) -> User:
    if not current_user.is_active:
        raise HTTPException(status_code=400, detail="用户已禁用")
    return current_user

@app.get("/users/me")
async def read_users_me(
    current_user: User = Depends(get_current_active_user)
):
    return current_user

5.4 全局依赖

from fastapi import FastAPI, Depends

async def verify_api_key(api_key: str = Header(...)):
    if api_key != "secret-api-key":
        raise HTTPException(status_code=403)

# 所有路由都需要 API Key
app = FastAPI(dependencies=[Depends(verify_api_key)])

6. 数据库集成

6.1 SQLAlchemy 2.0 异步配置

# core/database.py
from sqlalchemy.ext.asyncio import (
    create_async_engine,
    AsyncSession,
    async_sessionmaker
)
from sqlalchemy.orm import DeclarativeBase
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    DATABASE_URL: str = "postgresql+asyncpg://user:pass@localhost/db"
    DB_POOL_SIZE: int = 20
    DB_MAX_OVERFLOW: int = 10
    
    class Config:
        env_file = ".env"

settings = Settings()

# 创建异步引擎
engine = create_async_engine(
    settings.DATABASE_URL,
    pool_size=settings.DB_POOL_SIZE,
    max_overflow=settings.DB_MAX_OVERFLOW,
    pool_pre_ping=True,  # 使用前验证连接
    pool_recycle=3600,    # 1小时回收连接
    echo=False
)

# 创建会话工厂
AsyncSessionLocal = async_sessionmaker(
    engine,
    class_=AsyncSession,
    expire_on_commit=False
)

# 基类
class Base(DeclarativeBase):
    pass

# 依赖注入
async def get_db() -> AsyncGenerator[AsyncSession, None]:
    async with AsyncSessionLocal() as session:
        try:
            yield session
            await session.commit()
        except Exception:
            await session.rollback()
            raise

6.2 SQLAlchemy 2.0 模型定义

# models/user.py
from sqlalchemy import String, Boolean, DateTime, func
from sqlalchemy.orm import Mapped, mapped_column, relationship
from datetime import datetime
from core.database import Base

class User(Base):
    __tablename__ = "users"
    
    id: Mapped[int] = mapped_column(primary_key=True)
    username: Mapped[str] = mapped_column(String(50), unique=True, index=True)
    email: Mapped[str] = mapped_column(String(100), unique=True, index=True)
    hashed_password: Mapped[str] = mapped_column(String(100))
    is_active: Mapped[bool] = mapped_column(Boolean, default=True)
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        server_default=func.now()
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        server_default=func.now(),
        onupdate=func.now()
    )
    
    # 关系
    items: Mapped[list["Item"]] = relationship(back_populates="owner")

6.3 CRUD 操作

# repositories/user_repo.py
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from models.user import User
from schemas.user import UserCreate

class UserRepository:
    def __init__(self, db: AsyncSession):
        self.db = db
    
    async def get_by_id(self, user_id: int) -> User | None:
        result = await self.db.execute(
            select(User).where(User.id == user_id)
        )
        return result.scalar_one_or_none()
    
    async def get_by_email(self, email: str) -> User | None:
        result = await self.db.execute(
            select(User).where(User.email == email)
        )
        return result.scalar_one_or_none()
    
    async def create(self, user_data: UserCreate, hashed_password: str) -> User:
        user = User(
            username=user_data.username,
            email=user_data.email,
            hashed_password=hashed_password
        )
        self.db.add(user)
        await self.db.flush()
        await self.db.refresh(user)
        return user
    
    async def list(self, skip: int = 0, limit: int = 10) -> list[User]:
        result = await self.db.execute(
            select(User).offset(skip).limit(limit)
        )
        return result.scalars().all()

6.4 Alembic 数据库迁移

# 初始化 Alembic
alembic init alembic

# 创建迁移
alembic revision --autogenerate -m "create users table"

# 应用迁移
alembic upgrade head

# 回滚
alembic downgrade -1
# alembic/env.py 关键配置
from core.database import Base
target_metadata = Base.metadata

# 使用异步引擎
from sqlalchemy.ext.asyncio import create_async_engine
connectable = create_async_engine(settings.DATABASE_URL)

7. 认证与授权

7.1 JWT 认证

# core/security.py
from datetime import datetime, timedelta
from jose import JWTError, jwt
from passlib.context import CryptContext
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer

# 配置
SECRET_KEY = "your-secret-key-change-in-production"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30

# 密码哈希
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

# OAuth2 scheme
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

def verify_password(plain_password: str, hashed_password: str) -> bool:
    return pwd_context.verify(plain_password, hashed_password)

def get_password_hash(password: str) -> str:
    return pwd_context.hash(password)

def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
    to_encode = data.copy()
    expire = datetime.utcnow() + (expires_delta or timedelta(minutes=15))
    to_encode.update({"exp": expire})
    return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)

async def get_current_user(
    token: str = Depends(oauth2_scheme),
    db: AsyncSession = Depends(get_db)
) -> User:
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="无法验证凭据",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
    except JWTError:
        raise credentials_exception
    
    user = await UserRepository(db).get_by_username(username)
    if user is None:
        raise credentials_exception
    return user

7.2 登录端点

# api/auth.py
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm

router = APIRouter(prefix="/auth", tags=["认证"])

@router.post("/token")
async def login(
    form_data: OAuth2PasswordRequestForm = Depends(),
    db: AsyncSession = Depends(get_db)
):
    user_repo = UserRepository(db)
    user = await user_repo.get_by_username(form_data.username)
    
    if not user or not verify_password(form_data.password, user.hashed_password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    access_token = create_access_token(
        data={"sub": user.username},
        expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    )
    
    return {
        "access_token": access_token,
        "token_type": "bearer"
    }

7.3 受保护的路由

# api/users.py
from fastapi import APIRouter, Depends

router = APIRouter(prefix="/users", tags=["用户"])

@router.get("/me", response_model=UserResponse)
async def read_users_me(
    current_user: User = Depends(get_current_user)
):
    return current_user

@router.get("/", response_model=list[UserResponse])
async def read_users(
    skip: int = 0,
    limit: int = 10,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    # 只有管理员可以查看所有用户
    if not current_user.is_admin:
        raise HTTPException(status_code=403, detail="权限不足")
    
    return await UserRepository(db).list(skip=skip, limit=limit)

8. 中间件与CORS

8.1 CORS 中间件

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# 配置 CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000", "https://yourdomain.com"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

8.2 自定义中间件

import time
from fastapi import FastAPI, Request

app = FastAPI()

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response

8.3 请求日志中间件

import logging
from fastapi import FastAPI, Request
from starlette.middleware.base import BaseHTTPMiddleware

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class LoggingMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        logger.info(f"请求: {request.method} {request.url}")
        
        response = await call_next(request)
        
        logger.info(f"响应: {response.status_code}")
        return response

app = FastAPI()
app.add_middleware(LoggingMiddleware)

8.4 异常处理

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

app = FastAPI()

class CustomException(Exception):
    def __init__(self, status_code: int, detail: str):
        self.status_code = status_code
        self.detail = detail

@app.exception_handler(CustomException)
async def custom_exception_handler(request: Request, exc: CustomException):
    return JSONResponse(
        status_code=exc.status_code,
        content={"detail": exc.detail}
    )

@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    return JSONResponse(
        status_code=500,
        content={"detail": "服务器内部错误"}
    )

9. 后台任务与WebSocket

9.1 后台任务

from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

def send_email(email: str, message: str):
    """模拟发送邮件"""
    print(f"发送邮件到 {email}: {message}")

@app.post("/users/")
async def create_user(
    user: UserCreate,
    background_tasks: BackgroundTasks
):
    # 创建用户...
    
    # 添加后台任务
    background_tasks.add_task(
        send_email,
        email=user.email,
        message="欢迎注册!"
    )
    
    return {"message": "用户创建成功"}

9.2 使用 Celery 处理耗时任务

# tasks/email.py
from celery import Celery

celery_app = Celery(
    "worker",
    broker="redis://localhost:6379/0",
    backend="redis://localhost:6379/1"
)

@celery_app.task
def send_welcome_email(email: str):
    # 耗时的邮件发送逻辑
    pass

# api/users.py
from tasks.email import send_welcome_email

@app.post("/users/")
async def create_user(user: UserCreate):
    # 创建用户...
    
    # 异步发送邮件
    send_welcome_email.delay(user.email)
    
    return {"message": "用户创建成功"}

9.3 WebSocket

from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from typing import List

app = FastAPI()

class ConnectionManager:
    def __init__(self):
        self.active_connections: List[WebSocket] = []
    
    async def connect(self, websocket: WebSocket):
        await websocket.accept()
        self.active_connections.append(websocket)
    
    def disconnect(self, websocket: WebSocket):
        self.active_connections.remove(websocket)
    
    async def broadcast(self, message: str):
        for connection in self.active_connections:
            await connection.send_text(message)

manager = ConnectionManager()

@app.websocket("/ws/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: str):
    await manager.connect(websocket)
    try:
        while True:
            data = await websocket.receive_text()
            await manager.broadcast(f"客户端 {client_id}: {data}")
    except WebSocketDisconnect:
        manager.disconnect(websocket)

10. 项目结构最佳实践

10.1 推荐目录结构

myapp/
├── alembic/                # 数据库迁移
│   ├── versions/
│   └── env.py
├── app/
│   ├── __init__.py
│   ├── main.py             # 应用入口
│   ├── api/
│   │   ├── __init__.py
│   │   ├── deps.py         # 公共依赖
│   │   └── v1/
│   │       ├── __init__.py
│   │       ├── router.py   # 路由聚合
│   │       ├── users.py    # 用户路由
│   │       ├── items.py    # 物品路由
│   │       └── auth.py     # 认证路由
│   ├── core/
│   │   ├── __init__.py
│   │   ├── config.py       # 配置管理
│   │   ├── security.py     # 安全相关
│   │   └── database.py     # 数据库配置
│   ├── models/
│   │   ├── __init__.py
│   │   ├── user.py         # SQLAlchemy 模型
│   │   └── item.py
│   ├── schemas/
│   │   ├── __init__.py
│   │   ├── user.py         # Pydantic 模型
│   │   └── item.py
│   ├── services/
│   │   ├── __init__.py
│   │   ├── user_service.py # 业务逻辑
│   │   └── item_service.py
│   └── utils/
│       ├── __init__.py
│       └── helpers.py
├── tests/
│   ├── conftest.py
│   ├── test_users.py
│   └── test_items.py
├── .env                    # 环境变量
├── .gitignore
├── alembic.ini
├── Dockerfile
├── docker-compose.yml
├── pyproject.toml
└── README.md

10.2 应用工厂模式

# app/main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager

from app.core.config import settings
from app.core.database import engine, Base
from app.api.v1.router import api_router

@asynccontextmanager
async def lifespan(app: FastAPI):
    # 启动时执行
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    yield
    # 关闭时执行
    await engine.dispose()

def create_app() -> FastAPI:
    app = FastAPI(
        title=settings.APP_NAME,
        version=settings.VERSION,
        docs_url="/docs" if settings.DEBUG else None,
        redoc_url="/redoc" if settings.DEBUG else None,
    )
    
    # 中间件
    app.add_middleware(
        CORSMiddleware,
        allow_origins=settings.CORS_ORIGINS,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    
    # 路由
    app.include_router(api_router, prefix="/api/v1")
    
    # 健康检查
    @app.get("/health")
    async def health_check():
        return {"status": "healthy"}
    
    return app

app = create_app()

10.3 路由组织

# app/api/v1/router.py
from fastapi import APIRouter
from app.api.v1 import users, items, auth

api_router = APIRouter()
api_router.include_router(auth.router)
api_router.include_router(users.router)
api_router.include_router(items.router)
# app/api/v1/users.py
from fastapi import APIRouter, Depends
from app.api.deps import get_db, get_current_user

router = APIRouter(prefix="/users", tags=["用户"])

@router.get("/", response_model=list[UserResponse])
async def list_users(
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    pass

11. 测试策略

11.1 测试配置

# tests/conftest.py
import pytest
from httpx import AsyncClient, ASGITransport
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from app.main import app
from app.core.database import Base, get_db

# 测试数据库
TEST_DATABASE_URL = "postgresql+asyncpg://user:pass@localhost/test_db"

@pytest.fixture(scope="session")
async def engine():
    engine = create_async_engine(TEST_DATABASE_URL)
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    yield engine
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
    await engine.dispose()

@pytest.fixture
async def db(engine):
    async with AsyncSession(engine) as session:
        yield session

@pytest.fixture
async def client(db):
    async def override_get_db():
        yield db
    
    app.dependency_overrides[get_db] = override_get_db
    
    async with AsyncClient(
        transport=ASGITransport(app=app),
        base_url="http://test"
    ) as client:
        yield client
    
    app.dependency_overrides.clear()

11.2 编写测试

# tests/test_users.py
import pytest
from httpx import AsyncClient

@pytest.mark.asyncio
async def test_create_user(client: AsyncClient):
    response = await client.post(
        "/api/v1/users/",
        json={
            "username": "testuser",
            "email": "test@example.com",
            "password": "testpassword123"
        }
    )
    assert response.status_code == 201
    data = response.json()
    assert data["username"] == "testuser"
    assert data["email"] == "test@example.com"
    assert "password" not in data

@pytest.mark.asyncio
async def test_read_user(client: AsyncClient):
    # 先创建用户
    create_response = await client.post(
        "/api/v1/users/",
        json={
            "username": "testuser",
            "email": "test@example.com",
            "password": "testpassword123"
        }
    )
    user_id = create_response.json()["id"]
    
    # 获取用户
    response = await client.get(f"/api/v1/users/{user_id}")
    assert response.status_code == 200
    assert response.json()["username"] == "testuser"

@pytest.mark.asyncio
async def test_read_user_not_found(client: AsyncClient):
    response = await client.get("/api/v1/users/999")
    assert response.status_code == 404

11.3 运行测试

# 运行所有测试
pytest

# 运行特定测试文件
pytest tests/test_users.py

# 显示覆盖率
pytest --cov=app --cov-report=html

# 运行异步测试
pytest -xvs tests/

12. 生产部署

12.1 Dockerfile

# 多阶段构建
FROM python:3.12-slim as builder

WORKDIR /app
COPY pyproject.toml poetry.lock ./
RUN pip install poetry && poetry export -f requirements.txt -o requirements.txt

FROM python:3.12-slim

WORKDIR /app

# 安装依赖
COPY --from=builder /app/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# 复制应用代码
COPY . .

# 创建非 root 用户
RUN adduser --disabled-password --gecos "" appuser
USER appuser

# 运行
CMD ["gunicorn", "app.main:app", \
     "--worker-class", "uvicorn.workers.UvicornWorker", \
     "--workers", "4", \
     "--bind", "0.0.0.0:8000"]

12.2 docker-compose.yml

version: '3.8'

services:
  app:
    build: .
    ports:
      - "8000:8000"
    environment:
      - DATABASE_URL=postgresql+asyncpg://user:pass@db/app
      - REDIS_URL=redis://redis:6379/0
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_started
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
      interval: 30s
      timeout: 10s
      retries: 3

  db:
    image: postgres:15
    environment:
      - POSTGRES_USER=user
      - POSTGRES_PASSWORD=pass
      - POSTGRES_DB=app
    volumes:
      - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U user -d app"]
      interval: 10s
      timeout: 5s
      retries: 5

  redis:
    image: redis:7-alpine
    volumes:
      - redis_data:/data

volumes:
  postgres_data:
  redis_data:

12.3 生产配置

# app/core/config.py
from pydantic_settings import BaseSettings
from pydantic import ConfigDict

class Settings(BaseSettings):
    model_config = ConfigDict(env_file=".env", extra="ignore")
    
    APP_NAME: str = "My API"
    VERSION: str = "1.0.0"
    DEBUG: bool = False
    
    # 数据库
    DATABASE_URL: str
    DB_POOL_SIZE: int = 20
    DB_MAX_OVERFLOW: int = 10
    
    # Redis
    REDIS_URL: str = "redis://localhost:6379/0"
    
    # JWT
    SECRET_KEY: str
    ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
    
    # CORS
    CORS_ORIGINS: list[str] = ["https://yourdomain.com"]

settings = Settings()

12.4 Gunicorn 配置

# gunicorn.conf.py
import multiprocessing

# Worker 配置
workers = multiprocessing.cpu_count() * 2 + 1
worker_class = "uvicorn.workers.UvicornWorker"
bind = "0.0.0.0:8000"

# 超时配置
timeout = 120
keepalive = 5
graceful_timeout = 30

# 日志配置
accesslog = "-"
errorlog = "-"
loglevel = "info"

12.5 Nginx 配置

server {
    listen 80;
    server_name yourdomain.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name yourdomain.com;

    ssl_certificate /etc/nginx/ssl/cert.pem;
    ssl_certificate_key /etc/nginx/ssl/key.pem;

    location / {
        proxy_pass http://app:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        
        # WebSocket 支持
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

13. 性能优化

13.1 连接池优化

from sqlalchemy.ext.asyncio import create_async_engine

engine = create_async_engine(
    DATABASE_URL,
    pool_size=20,          # 每个 worker 的最大连接数
    max_overflow=10,       # 超出 pool_size 后的额外连接
    pool_pre_ping=True,    # 使用前验证连接
    pool_recycle=3600,     # 1 小时回收连接
    pool_timeout=30,       # 获取连接超时
    echo=False             # 生产环境关闭 SQL 日志
)

计算公式:

  • 总连接数 = Workers × (pool_size + max_overflow)
  • 例:4 workers × (20 + 10) = 120 连接
  • 确保:总连接数 < 数据库最大连接数

13.2 异步优化

import asyncio
from fastapi import FastAPI

app = FastAPI()

# ✅ 正确:异步 I/O 操作
@app.get("/async-example")
async def async_example():
    result = await async_database_query()
    return result

# ✅ 正确:CPU 密集型操作使用线程池
@app.get("/cpu-intensive")
async def cpu_intensive():
    result = await asyncio.to_thread(heavy_computation)
    return result

# ❌ 错误:在 async def 中使用同步数据库
@app.get("/bad-example")
async def bad_example():
    # 这会阻塞事件循环!
    result = sync_database.query(User).all()
    return result

13.3 缓存策略

from fastapi import FastAPI
from redis import asyncio as aioredis
import json

app = FastAPI()
redis = aioredis.from_url("redis://localhost:6379")

async def get_cached(key: str):
    data = await redis.get(key)
    if data:
        return json.loads(data)
    return None

async def set_cached(key: str, value: dict, expire: int = 300):
    await redis.set(key, json.dumps(value), ex=expire)

@app.get("/items/{item_id}")
async def read_item(item_id: int, db: AsyncSession = Depends(get_db)):
    # 尝试从缓存获取
    cache_key = f"item:{item_id}"
    cached = await get_cached(cache_key)
    if cached:
        return cached
    
    # 从数据库获取
    item = await db.get(Item, item_id)
    if not item:
        raise HTTPException(status_code=404)
    
    # 存入缓存
    result = ItemResponse.from_orm(item).dict()
    await set_cached(cache_key, result, expire=300)
    
    return result

13.4 查询优化

from sqlalchemy.orm import selectinload, joinedload

# ❌ N+1 查询问题
users = await db.execute(select(User))
for user in users.scalars():
    items = await db.execute(
        select(Item).where(Item.owner_id == user.id)
    )

# ✅ 使用 eager loading
users = await db.execute(
    select(User).options(selectinload(User.items))
)

# ✅ 使用 joinedload(适用于一对一关系)
users = await db.execute(
    select(User).options(joinedload(User.profile))
)

14. 学习资源

14.1 官方资源

  • 官方文档: https://fastapi.tiangolo.com/
  • GitHub: https://github.com/tiangolo/fastapi
  • FastAPI 排练场: https://fastapi.tiangolo.com/tutorial/first-steps/

14.2 推荐教程

  • FastAPI Complete Guide 2026: https://devtoolbox.dedyn.io/blog/fastapi-complete-guide
  • FastAPI Tutorial 2026: https://techoral.com/python/python-fastapi-guide.html
  • FastAPI Production Guide: https://softaims.com/blog/fastapi-production-api-guide-2026

14.3 核心依赖库

库 用途 版本
FastAPI Web 框架 0.115+
Pydantic 数据验证 2.10+
SQLAlchemy ORM 2.0+
asyncpg PostgreSQL 异步驱动 0.29+
uvicorn ASGI 服务器 0.34+
gunicorn 进程管理 22.0+
python-jose JWT 处理 3.3+
passlib 密码哈希 1.7+
alembic 数据库迁移 1.13+
redis 缓存/消息队列 5.0+
httpx 异步 HTTP 客户端 0.27+
pytest 测试框架 8.0+

14.4 FastAPI vs Flask vs Django

特性 FastAPI Flask Django
异步支持 ✅ 原生 ❌ 需扩展 ✅ 3.0+
自动文档 ✅ OpenAPI ❌ 需扩展 ✅ DRF
数据验证 ✅ Pydantic ❌ 需扩展 ✅ Serializer
性能 ⭐⭐⭐⭐⭐ ⭐⭐⭐ ⭐⭐⭐
学习曲线 低 低 中
适用场景 API 简单应用 全栈应用

14.5 生产环境检查清单

✅ 配置管理
   □ 使用 pydantic-settings 管理环境变量
   □ 敏感信息不硬编码
   □ 区分开发/生产配置

✅ 数据库
   □ 使用异步 SQLAlchemy 2.0
   □ 正确配置连接池
   □ 使用 Alembic 管理迁移
   □ 设置 pool_pre_ping=True

✅ 安全
   □ 实现 JWT 认证
   □ 配置 CORS
   □ 使用 HTTPS
   □ 输入验证(Pydantic)
   □ SQL 注入防护(SQLAlchemy)

✅ 性能
   □ 避免阻塞事件循环
   □ 使用连接池
   □ 实现缓存策略
   □ 优化数据库查询

✅ 部署
   □ 使用 Docker 多阶段构建
   □ Gunicorn + Uvicorn Workers
   □ 健康检查端点
   □ 结构化日志
   □ 监控和告警

✅ 测试
   □ 单元测试
   □ 集成测试
   □ 测试覆盖率 > 80%

附录:常用代码片段

A.1 快速 CRUD 路由

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select

router = APIRouter()

@router.get("/", response_model=list[ResponseSchema])
async def list_items(
    skip: int = 0,
    limit: int = 10,
    db: AsyncSession = Depends(get_db)
):
    result = await db.execute(select(Model).offset(skip).limit(limit))
    return result.scalars().all()

@router.post("/", response_model=ResponseSchema, status_code=201)
async def create_item(
    item: CreateSchema,
    db: AsyncSession = Depends(get_db)
):
    db_item = Model(**item.dict())
    db.add(db_item)
    await db.commit()
    await db.refresh(db_item)
    return db_item

@router.get("/{item_id}", response_model=ResponseSchema)
async def get_item(
    item_id: int,
    db: AsyncSession = Depends(get_db)
):
    item = await db.get(Model, item_id)
    if not item:
        raise HTTPException(status_code=404, detail="未找到")
    return item

@router.put("/{item_id}", response_model=ResponseSchema)
async def update_item(
    item_id: int,
    item: UpdateSchema,
    db: AsyncSession = Depends(get_db)
):
    db_item = await db.get(Model, item_id)
    if not db_item:
        raise HTTPException(status_code=404, detail="未找到")
    
    for key, value in item.dict(exclude_unset=True).items():
        setattr(db_item, key, value)
    
    await db.commit()
    await db.refresh(db_item)
    return db_item

@router.delete("/{item_id}", status_code=204)
async def delete_item(
    item_id: int,
    db: AsyncSession = Depends(get_db)
):
    item = await db.get(Model, item_id)
    if not item:
        raise HTTPException(status_code=404, detail="未找到")
    
    await db.delete(item)
    await db.commit()

A.2 标准错误响应

from fastapi import HTTPException, Request
from fastapi.responses import JSONResponse

class AppException(Exception):
    def __init__(self, status_code: int, message: str, detail: str = None):
        self.status_code = status_code
        self.message = message
        self.detail = detail

@app.exception_handler(AppException)
async def app_exception_handler(request: Request, exc: AppException):
    return JSONResponse(
        status_code=exc.status_code,
        content={
            "error": {
                "message": exc.message,
                "detail": exc.detail,
                "status_code": exc.status_code
            }
        }
    )

# 使用
raise AppException(
    status_code=404,
    message="资源不存在",
    detail=f"ID 为 {item_id} 的物品不存在"
)

A.3 分页响应

from pydantic import BaseModel
from typing import Generic, TypeVar

T = TypeVar("T")

class PaginatedResponse(BaseModel, Generic[T]):
    items: list[T]
    total: int
    page: int
    size: int
    pages: int

async def paginate(
    query,
    db: AsyncSession,
    page: int = 1,
    size: int = 10
) -> PaginatedResponse:
    # 获取总数
    count_query = select(func.count()).select_from(query.subquery())
    total = await db.scalar(count_query)
    
    # 获取数据
    result = await db.execute(
        query.offset((page - 1) * size).limit(size)
    )
    items = result.scalars().all()
    
    return PaginatedResponse(
        items=items,
        total=total,
        page=page,
        size=size,
        pages=(total + size - 1) // size
    )

📝 文档维护者:小码
🔄 最后更新:2026-06-21
💡 建议:先从官方文档开始,然后跟着生产级教程实践