Skip to content

Instantly share code, notes, and snippets.

@Xsir0
Created September 11, 2025 06:46
Show Gist options
  • Select an option

  • Save Xsir0/f761826eb285e6a127f1277ca6e434c0 to your computer and use it in GitHub Desktop.

Select an option

Save Xsir0/f761826eb285e6a127f1277ca6e434c0 to your computer and use it in GitHub Desktop.
本项目是一个基于 FastAPI 的标准 Web 应用模板,采用分层架构设计,包含完整的认证系统、数据库操作、定时任务等功能模块。该模板旨在为新项目提供一个标准化的起点,减少重复工作,提高开发效率。
# FastAPI 标准项目模板文档
## 1. 项目概述
本项目是一个基于 FastAPI 的标准 Web 应用模板,采用分层架构设计,包含完整的认证系统、数据库操作、定时任务等功能模块。该模板旨在为新项目提供一个标准化的起点,减少重复工作,提高开发效率。
### 1.1 技术栈
- **核心框架**: FastAPI
- **ASGI 服务器**: Uvicorn
- **数据库**: SQLAlchemy (支持 SQLite, PostgreSQL, MySQL)
- **数据库迁移**: Alembic
- **数据验证**: Pydantic
- **配置管理**: Pydantic Settings
- **认证安全**: JWT, OAuth2, Passlib
- **定时任务**: APScheduler
- **测试框架**: Pytest
- **代码质量**: Black, Isort, Flake8, MyPy
- **容器化**: Docker
### 1.2 项目特性
- 完整的用户认证系统(注册、登录、JWT Token 管理)
- OAuth2 集成(支持 Google 登录)
- 用户权限管理
- 数据库 CRUD 操作封装
- 定时任务调度系统
- 日志记录系统
- API 文档(Swagger UI, ReDoc)
- 响应统一包装
- 异常处理机制
- CORS 配置
- Docker 容器化支持
## 2. 项目结构
```text
fastapi-template/
├── app/ # 应用核心代码
│ ├── __init__.py
│ ├── main.py # FastAPI 应用实例和根路由
│ ├── core/ # 核心配置、安全依赖项
│ │ ├── __init__.py
│ │ ├── config.py # 配置设置(从环境变量读取)
│ │ ├── security.py # 认证、密码工具
│ │ ├── database.py # 数据库连接和会话管理
│ │ ├── response_wrapper.py # 响应包装器
│ │ ├── request_logging.py # 请求日志记录
│ │ └── exception_handlers.py # 全局异常处理
│ ├── api/ # 所有 API 路由端点
│ │ ├── __init__.py
│ │ ├── deps.py # 共享依赖项(如数据库会话)
│ │ └── v1/ # API 版本化 (v1)
│ │ ├── __init__.py
│ │ ├── endpoints/ # 按模块分组的端点
│ │ │ ├── __init__.py
│ │ │ ├── auth.py
│ │ │ ├── users.py
│ │ │ └── items.py
│ │ └── routers.py # 路由聚合
│ ├── models/ # SQLAlchemy 数据模型
│ │ ├── __init__.py
│ │ ├── user.py
│ │ └── item.py
│ ├── schemas/ # Pydantic 模型(序列化器/反序列化器)
│ │ ├── __init__.py
│ │ ├── user.py
│ │ └── item.py
│ ├── services/ # 业务逻辑层
│ │ ├── __init__.py
│ │ ├── user_service.py
│ │ └── item_service.py
│ ├── crud/ # 数据库 CRUD 操作
│ │ ├── __init__.py
│ │ ├── user.py
│ │ └── item.py
│ └── tasks/ # 定时任务系统
│ ├── __init__.py
│ ├── scheduler.py # 任务调度器
│ ├── task_manager.py # 任务管理器
│ └── jobs/ # 具体任务实现
├── tests/ # 测试文件
│ ├── __init__.py
│ ├── conftest.py # Pytest 配置和固件
│ ├── test_api/ # API 端点测试
│ └── test_services/ # 服务层测试
├── alembic/ # 数据库迁移(如果使用 Alembic)
│ ├── versions/
│ └── env.py
├── static/ # 静态文件(可选)
├── templates/ # 模板文件(如 Jinja2,可选)
├── docs/ # 项目文档
├── requirements.txt # 项目依赖
├── pyproject.toml # 项目配置
├── Dockerfile # Docker 容器化
├── .env # 环境变量(切勿提交!用于开发)
├── .gitignore # Git 忽略文件
└── README.md # 项目说明文档
```
## 3. 核心组件详解
### 3.1 应用入口 (app/main.py)
应用入口文件负责创建 FastAPI 实例、配置中间件、注册路由和管理应用生命周期。
关键特性:
- 应用生命周期管理(启动和关闭)
- 中间件配置(CORS、Session、日志等)
- 路由注册
- 异常处理配置
- API 文档配置
### 3.2 配置管理 (app/core/config.py)
使用 Pydantic Settings 管理应用配置,支持从环境变量读取配置。
配置项包括:
- 应用基本信息(名称、版本、调试模式)
- 服务器配置(主机、端口)
- 数据库配置(连接URL)
- 安全配置(密钥、Token过期时间、算法)
- OAuth 配置(客户端ID、密钥、回调URL)
- CORS 配置(允许的源、方法、头部)
- 日志配置
### 3.3 数据库层
#### 3.3.1 数据库连接 (app/core/database.py)
负责数据库引擎创建、会话管理和依赖注入。
#### 3.3.2 数据模型 (app/models/)
使用 SQLAlchemy 定义数据模型,每个模型对应数据库中的一张表。
#### 3.3.3 CRUD 操作 (app/crud/)
封装基本的数据库操作(创建、读取、更新、删除),提供可重用的数据库操作方法。
### 3.4 业务逻辑层 (app/services/)
实现具体的业务逻辑,调用 CRUD 层进行数据操作,处理业务规则和流程。
### 3.5 API 层 (app/api/)
#### 3.5.1 路由定义
使用 FastAPI 的路由装饰器定义 API 端点,处理 HTTP 请求。
#### 3.5.2 数据验证 (app/schemas/)
使用 Pydantic 模型进行请求数据验证和响应数据序列化。
#### 3.5.3 依赖管理 (app/api/deps.py)
定义和管理 API 端点的依赖项,如数据库会话、当前用户等。
### 3.6 认证系统
完整的用户认证和授权系统,包括:
- 用户注册和登录
- JWT Token 生成和验证
- OAuth2 集成(Google 登录)
- 密码加密和验证
- Token 黑名单管理
### 3.7 定时任务系统 (app/tasks/)
基于 APScheduler 的定时任务系统,支持:
- 任务注册和管理
- 任务调度和执行
- 任务状态监控
- 动态任务添加和删除
### 3.8 日志系统
统一的日志记录系统,包括:
- 请求日志记录
- 业务操作日志
- 数据库操作日志
- 系统启动日志
### 3.9 异常处理
全局异常处理机制,统一处理应用中的各种异常,返回标准化的错误响应。
## 4. 开发规范
### 4.1 代码规范
- 使用 Black 进行代码格式化
- 使用 Isort 进行 import 排序
- 使用 Flake8 进行代码检查
- 使用 MyPy 进行类型检查
### 4.2 Git 提交规范
- 使用 conventional commits 规范
- 提交信息应清晰描述变更内容
- 每次提交应尽量小且功能单一
### 4.3 API 设计规范
- 遵循 RESTful API 设计原则
- 使用合适的 HTTP 状态码
- 统一的响应格式
- 详细的 API 文档
### 4.4 数据库设计规范
- 使用 Alembic 进行数据库迁移
- 合理设计表结构和索引
- 遵循数据库范式设计
- 统一的命名规范
## 5. 部署指南
### 5.1 环境配置
- 设置环境变量
- 配置数据库连接
- 配置安全密钥
- 配置 OAuth 参数
### 5.2 Docker 部署
使用提供的 Dockerfile 进行容器化部署:
```bash
# 构建镜像
docker build -t <image-name> .
# 运行容器
docker run -d -p 8000:8000 <container-name>
```
### 5.3 生产环境部署
- 使用 Gunicorn 或 Uvicorn 运行应用
- 配置 Nginx 作为反向代理
- 配置 SSL 证书
- 设置日志轮转
- 配置监控和告警
## 6. 测试指南
### 6.1 单元测试
使用 Pytest 编写单元测试,测试各个模块的功能。
### 6.2 集成测试
测试模块间的集成和交互,确保系统整体功能正常。
### 6.3 API 测试
测试 API 端点的功能和性能,确保接口符合设计要求。
## 7. 附录
### 7.1 核心文件模板
#### app/main.py
```python
from fastapi import FastAPI
from app.api.v1.routers import api_router
from app.core.config import settings
app = FastAPI(
title=settings.APP_NAME,
version=settings.APP_VERSION,
description="FastAPI Template Application",
)
app.include_router(api_router, prefix="/api/v1")
@app.get("/")
async def root():
return {"message": "Welcome to FastAPI Template Application"}
```
#### app/core/config.py
```python
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
APP_NAME: str = "FastAPI Template"
APP_VERSION: str = "1.0.0"
DEBUG: bool = False
DATABASE_URL: str = "sqlite:///./app.db"
SECRET_KEY: str = "your-secret-key"
class Config:
env_file = ".env"
settings = Settings()
```
#### app/core/database.py
```python
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from app.core.config import settings
engine = create_engine(settings.DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
```
#### app/models/user.py
```python
from sqlalchemy import Column, Integer, String
from app.core.database import Base
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
email = Column(String, unique=True, index=True)
hashed_password = Column(String)
```
#### app/schemas/user.py
```python
from pydantic import BaseModel
class UserBase(BaseModel):
email: str
class UserCreate(UserBase):
password: str
class User(UserBase):
id: int
class Config:
from_attributes = True
```
#### app/crud/user.py
```python
from sqlalchemy.orm import Session
from app.models.user import User
from app.schemas.user import UserCreate
def get_user(db: Session, user_id: int):
return db.query(User).filter(User.id == user_id).first()
def get_user_by_email(db: Session, email: str):
return db.query(User).filter(User.email == email).first()
def create_user(db: Session, user: UserCreate):
db_user = User(email=user.email, hashed_password=user.password)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
```
#### app/api/v1/endpoints/users.py
```python
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.api.deps import get_db
from app.schemas.user import User, UserCreate
from app.crud.user import create_user, get_user
router = APIRouter()
@router.post("/", response_model=User)
def create_user_endpoint(user: UserCreate, db: Session = Depends(get_db)):
db_user = get_user_by_email(db, email=user.email)
if db_user:
raise HTTPException(status_code=400, detail="Email already registered")
return create_user(db=db, user=user)
```
#### app/api/v1/routers.py
```python
from fastapi import APIRouter
from app.api.v1.endpoints import users, auth
api_router = APIRouter()
api_router.include_router(users.router, prefix="/users", tags=["users"])
api_router.include_router(auth.router, prefix="/auth", tags=["auth"])
```
#### pyproject.toml
```toml
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "fastapi-template"
version = "1.0.0"
description = "FastAPI Template Project"
dependencies = [
# FastAPI 核心依赖
"fastapi>=0.104.0",
"uvicorn[standard]>=0.24.0",
# 数据库相关
"sqlalchemy>=2.0.0",
"alembic>=1.12.0",
# 数据验证和序列化
"pydantic[email]>=2.4.0",
"pydantic-settings>=2.0.0",
# 安全认证
"python-jose[cryptography]>=3.3.0",
"passlib[bcrypt]>=1.7.0",
"python-multipart>=0.0.6",
# OAuth认证
"authlib>=1.2.0",
"requests>=2.31.0",
"itsdangerous>=2.2.0",
"apscheduler>=3.11.0",
"aiohttp>=3.12.15",
"pyyaml>=6.0.2",
]
[project.optional-dependencies]
dev = [
# 开发和测试
"pytest>=7.4.0",
"pytest-asyncio>=0.21.0",
"httpx>=0.25.0",
# 代码质量工具
"black>=23.0.0",
"isort>=5.12.0",
"flake8>=6.0.0",
"mypy>=1.0.0",
# 开发工具
"pre-commit>=3.0.0",
]
```
#### Dockerfile
```dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
```
#### .env.example
```env
APP_NAME=FastAPI Template
DEBUG=True
DATABASE_URL=sqlite:///./app.db
SECRET_KEY=your-secret-key-change-in-production
```
### 7.2 核心框架
#### 1. FastAPI
- **版本**: >=0.104.0
- **用途**: 项目的核心Web框架,用于构建API
- **特点**:
- 高性能异步框架
- 基于Starlette和Pydantic
- 自动生成交互式API文档
- **使用方法**:
```python
from fastapi import FastAPI
app = FastAPI(
title="FastAPI Test App",
version="1.0.0",
description="FastAPI Template Application with Authentication"
)
```
#### 2. Uvicorn
- **版本**: >=0.24.0
- **用途**: ASGI服务器,用于运行FastAPI应用
- **特点**:
- 基于uvloop和httptools的快速实现
- 支持异步处理
- **使用方法**:
```bash
uvicorn app.main:app --reload
```
### 7.3 数据库相关
#### 3. SQLAlchemy
- **版本**: >=2.0.0
- **用途**: ORM框架,用于数据库操作
- **特点**:
- 支持多种数据库后端
- 提供高级ORM和核心SQL表达式语言
- **使用方法**:
```python
from sqlalchemy import Column, Integer, String
from app.database import Base
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
```
#### 4. Alembic
- **版本**: >=1.12.0
- **用途**: 数据库迁移工具
- **特点**:
- 支持数据库版本控制
- 自动生成迁移脚本
- **使用方法**:
```bash
alembic revision --autogenerate -m "Migration message"
alembic upgrade head
```
### 7.4数据验证和序列化
#### 5. Pydantic
- **版本**: >=2.4.0
- **用途**: 数据验证和设置管理
- **特点**:
- 基于类型提示的数据验证
- 与FastAPI深度集成
- **使用方法**:
```python
from pydantic import BaseModel
class UserCreate(BaseModel):
email: str
password: str
```
#### 6. Pydantic Settings
- **版本**: >=2.0.0
- **用途**: 应用配置管理
- **特点**:
- 环境变量自动加载
- 类型安全的配置
- **使用方法**:
```python
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
DATABASE_URL: str = "sqlite:///./test.db"
```
### 7.5安全认证
#### 7. Python-Jose
- **版本**: >=3.3.0
- **用途**: JWT Token处理
- **特点**:
- 支持JWT编码和解码
- 支持多种加密算法
- **使用方法**:
```python
from jose import jwt
token = jwt.encode(data, secret_key, algorithm="HS256")
```
#### 8. Passlib
- **版本**: >=1.7.0
- **用途**: 密码哈希处理
- **特点**:
- 支持多种哈希算法
- 自动处理盐值
- **使用方法**:
```python
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"])
hashed = pwd_context.hash("password")
```
#### 9. Authlib
- **版本**: >=1.2.0
- **用途**: OAuth认证支持
- **特点**:
- 支持多种OAuth提供商
- 与Starlette集成
- **使用方法**:
```python
from authlib.integrations.starlette_client import OAuth
oauth = OAuth()
oauth.register(
name='google',
client_id=settings.GOOGLE_CLIENT_ID,
client_secret=settings.GOOGLE_CLIENT_SECRET
)
```
### 7.6定时任务
#### 10. APScheduler
- **版本**: >=3.10.0
- **用途**: 定时任务调度
- **特点**:
- 支持多种调度方式(Cron、间隔、日期)
- 异步任务支持
- **使用方法**:
```python
from apscheduler.schedulers.asyncio import AsyncIOScheduler
scheduler = AsyncIOScheduler()
scheduler.add_job(func, 'interval', minutes=30)
scheduler.start()
```
### 7.7测试框架
#### 11. Pytest
- **版本**: >=7.4.0
- **用途**: 单元测试框架
- **特点**:
- 简单易用的测试编写
- 丰富的插件生态系统
- **使用方法**:
```python
def test_example():
assert 1 + 1 == 2
```
#### 12. Pytest-Asyncio
- **版本**: >=0.21.0
- **用途**: 异步测试支持
- **特点**:
- 支持异步测试函数
- 与pytest无缝集成
- **使用方法**:
```python
import pytest
@pytest.mark.asyncio
async def test_async_example():
result = await async_function()
assert result is not None
```
#### 13. HTTPX
- **版本**: >=0.25.0
- **用途**: HTTP客户端,用于API测试
- **特点**:
- 支持异步和同步请求
- 与pytest集成良好
- **使用方法**:
```python
import httpx
async with httpx.AsyncClient() as client:
response = await client.get("http://example.com")
```
### 7.8LLM模块依赖
#### 14. Aiohttp
- **版本**: >=3.8.0
- **用途**: 异步HTTP客户端,用于LLM API调用
- **特点**:
- 高性能异步HTTP客户端
- 支持WebSocket
- **使用方法**:
```python
import aiohttp
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
data = await response.json()
```
#### 15. PyYAML
- **版本**: >=6.0
- **用途**: YAML配置文件解析
- **特点**:
- 支持YAML格式读写
- 与Python数据结构无缝转换
- **使用方法**:
```python
import yaml
with open("config.yaml", "r") as f:
config = yaml.safe_load(f)
```
### 7.9开发工具
#### 16. Black
- **版本**: >=23.0.0
- **用途**: 代码格式化工具
- **特点**:
- 无争议的代码格式化
- 自动格式化Python代码
- **使用方法**:
```bash
black app/
```
#### 17. Isort
- **版本**: >=5.12.0
- **用途**: Python导入语句排序
- **特点**:
- 自动排序和分组导入语句
- 支持多种配置选项
- **使用方法**:
```bash
isort app/
```
#### 18. Flake8
- **版本**: >=6.0.0
- **用途**: 代码质量检查工具
- **特点**:
- 检查PEP8规范
- 发现潜在错误
- **使用方法**:
```bash
flake8 app/
```
#### 19. MyPy
- **版本**: >=1.0.0
- **用途**: 静态类型检查
- **特点**:
- 检查类型错误
- 提高代码质量
- **使用方法**:
```bash
mypy app/
```
#### 20. Pre-commit
- **版本**: >=3.0.0
- **用途**: Git钩子管理工具
- **特点**:
- 自动化代码检查
- 提交前验证
- **使用方法**:
```bash
pre-commit run --all-files
```
#### 21. PyMySQL
- **版本**: >=1.1.0
- **用途**: MySQL数据库驱动
- **特点**:
- 纯Python实现
- MySQL兼容
- **使用方法**:
```python
# 在requirements.txt中添加
PyMySQL>=1.1.0
```
### 7.10其他依赖
#### 22. Python-Multipart
- **版本**: >=0.0.6
- **用途**: 处理multipart/form-data
- **特点**:
- 支持文件上传
- 与FastAPI集成
- **使用方法**:
```python
from fastapi import File, UploadFile
@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):
contents = await file.read()
```
#### 23. Itsdangerous
- **版本**: >=2.1.0
- **用途**: 数据签名和序列化
- **特点**:
- 安全的数据序列化
- 防止数据篡改
- **使用方法**:
```python
from itsdangerous import URLSafeTimedSerializer
serializer = URLSafeTimedSerializer(secret_key)
token = serializer.dumps(data)
```
### 7.11环境配置
#### 开发环境要求
- Python版本: >=3.11
- 依赖管理: uv (推荐) 或 pip
- 数据库: SQLite (默认)、PostgreSQL 或 MySQL
#### 环境变量配置
在 `.env` 文件中配置以下变量:
```env
# 应用配置
APP_NAME=FastAPI Test App
APP_VERSION=1.0.0
DEBUG=False
# 数据库配置
DATABASE_URL=sqlite:///./test.db
# 安全配置
SECRET_KEY=your-super-secret-key-change-this-in-production
ACCESS_TOKEN_EXPIRE_MINUTES=30
# OAuth配置 (可选)
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
GOOGLE_REDIRECT_URI=http://localhost:8000/api/v1/auth/google/callback
# 前端URL
FRONTEND_URL=http://localhost:3000
```
### 7.12启动项目
#### 使用uv (推荐)
```bash
# 安装依赖
uv sync
# 启动开发服务器
uv run uvicorn app.main:app --reload
# 运行测试
uv run pytest
```
### 7.13数据库初始化
```bash
# 创建初始迁移
alembic revision --autogenerate -m "Initial migration"
# 应用迁移
alembic upgrade head
```
### 7.14API文档
启动服务器后,可以通过以下地址访问API文档:
- Swagger UI: http://localhost:8000/docs (需要登录)
- ReDoc: http://localhost:8000/redoc (需要登录)
### 7.15测试
运行测试:
```bash
# 运行所有测试
pytest
# 运行特定测试文件
pytest tests/test_main.py
# 详细输出
pytest -v
```
### 7.16代码质量
```bash
# 代码格式化
black app/ tests/
# 导入排序
isort app/ tests/
# 代码检查
flake8 app/ tests/
# 类型检查
mypy app/
# 运行所有检查
pre-commit run --all-files
```
---
*本文档为 FastAPI 项目标准模板文档,旨在为新项目提供标准化的架构和开发规范参考。*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment