FastAPI项目模板Prompt

FastAPI 项目配置

此文件为使用 Claude Code 进行 FastAPI Web 应用开发提供具体指导。

项目概述

这是一个为现代API开发优化的FastAPI应用项目,具有自动文档生成、类型提示和异步支持功能。

FastAPI 专用开发命令

项目管理

  • uvicorn app.main:app --reload - 启动带自动重载的开发服务器
  • uvicorn app.main:app --host 0.0.0.0 --port 8000 - 在所有接口上启动服务器
  • uvicorn app.main:app --workers 4 - 启动多进程服务器

数据库管理

  • alembic init alembic - 初始化 Alembic 迁移
  • alembic revision --autogenerate -m "message" - 创建迁移
  • alembic upgrade head - 应用迁移
  • alembic downgrade -1 - 回滚一个迁移

开发工具

  • python -m pytest - 运行测试
  • python -m pytest --cov=app - 运行带覆盖率的测试
  • mypy app/ - 类型检查
  • black app/ - 代码格式化

FastAPI 项目结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
myproject/
├── app/ # 应用包
│ ├── __init__.py
│ ├── main.py # FastAPI 应用
│ ├── core/ # 核心配置
│ │ ├── __init__.py
│ │ ├── config.py # 设置
│ │ └── security.py # 身份验证
│ ├── api/ # API 路由
│ │ ├── __init__.py
│ │ ├── deps.py # 依赖项
│ │ └── v1/
│ │ ├── __init__.py
│ │ ├── api.py # API 路由器
│ │ └── endpoints/
│ ├── models/ # 数据库模型
│ │ ├── __init__.py
│ │ ├── base.py
│ │ └── user.py
│ ├── schemas/ # Pydantic 模式
│ │ ├── __init__.py
│ │ └── user.py
│ ├── repositories/ # 数据访问层
│ │ ├── __init__.py
│ │ └── user.py
│ ├── services/ # 业务逻辑
│ │ ├── __init__.py
│ │ └── auth.py
│ └── db/ # 数据库配置
│ ├── __init__.py
│ └── database.py
├── alembic/ # 数据库迁移
├── tests/ # 测试文件
├── requirements.txt # 依赖项
└── docker-compose.yml # Docker 配置

FastAPI 应用设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# app/main.py
from fastapi import FastAPI
from app.core.config import settings
from app.api.v1.api import api_router

app = FastAPI(
title=settings.PROJECT_NAME,
version=settings.VERSION,
openapi_url=f"/api/v1/openapi.json"
)

# 包含路由器
app.include_router(api_router, prefix="/api/v1")

@app.get("/")
async def root():
return {"message": "欢迎使用 FastAPI"}

配置管理

1
2
3
4
5
6
7
8
9
10
11
12
13
# app/core/config.py
from pydantic import BaseSettings

class Settings(BaseSettings):
PROJECT_NAME: str = "FastAPI App"
VERSION: str = "1.0.0"
SECRET_KEY: str
DATABASE_URL: str

class Config:
env_file = ".env"

settings = Settings()

FastAPI 最佳实践

API 设计

  • 使用 Pydantic 模型进行请求/响应验证
  • 实现适当的 HTTP 状态码
  • 添加全面的 API 文档
  • 为通用功能使用依赖注入
  • 实现适当的错误处理

数据库集成

  • 使用带异步支持的 SQLAlchemy
  • 为数据访问实现仓储模式
  • 使用 Alembic 进行数据库迁移
  • 添加适当的数据库连接池
  • 实现数据库健康检查

身份验证与安全

  • 使用 JWT 令牌进行身份验证
  • 实现带作用域的 OAuth2
  • 为 API 端点添加速率限制
  • 在生产环境中使用 HTTPS
  • 实现适当的 CORS 配置

性能优化

  • 为 I/O 操作使用 async/await
  • 实现响应缓存
  • 添加数据库查询优化
  • 使用连接池
  • 监控应用性能

测试策略

测试组织

1
2
3
4
5
6
7
8
# tests/conftest.py
import pytest
from fastapi.testclient import TestClient
from app.main import app

@pytest.fixture
def client():
return TestClient(app)

测试类型

  • 单元测试 用于业务逻辑
  • 集成测试 用于 API 端点
  • 数据库测试 使用测试夹具
  • 身份验证测试 用于安全性

部署考虑

生产环境设置

  • 使用多进程的 Uvicorn
  • 实现适当的日志记录和监控
  • 设置反向代理(Nginx)
  • 使用环境变量进行配置
  • 实现健康检查

Docker 配置

1
2
3
4
5
6
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0"]

环境变量

1
2
3
SECRET_KEY=your-secret-key
DATABASE_URL=postgresql://user:pass@host/db
REDIS_URL=redis://localhost:6379

常见 FastAPI 模式

依赖注入

1
2
3
4
5
6
from fastapi import Depends
from app.db.database import get_db

@app.get("/users/")
async def get_users(db: Session = Depends(get_db)):
return users

后台任务

1
2
3
4
5
6
from fastapi import BackgroundTasks

@app.post("/send-email/")
async def send_email(background_tasks: BackgroundTasks):
background_tasks.add_task(send_email_task)
return {"message": "邮件已发送"}

中间件

1
2
3
4
@app.middleware("http")
async def add_process_time_header(request, call_next):
response = await call_next(request)
return response

开发工作流程

开始使用

  1. 克隆仓库
  2. 创建虚拟环境:python -m venv venv
  3. 安装依赖:pip install -r requirements.txt
  4. 设置环境变量
  5. 运行迁移:alembic upgrade head
  6. 启动服务器:uvicorn app.main:app --reload

代码质量

  • Black - 代码格式化
  • isort - 导入排序
  • mypy - 类型检查
  • pytest - 测试框架
  • flake8 - 代码检查