You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
13 KiB
13 KiB
系统架构设计
文档版本:v1.0
最后更新:2025-01-27
目录
分层架构
系统采用经典的四层架构设计,职责清晰,易于维护和扩展。
┌─────────────────────────────────────────┐
│ API 层 (FastAPI) │
│ - 路由定义 │
│ - 请求验证 │
│ - 响应格式化 │
└─────────────────┬───────────────────────┘
│
┌─────────────────▼───────────────────────┐
│ 业务逻辑层 (Services) │
│ - 项目管理服务 │
│ - 分镜管理服务 │
│ - 资源管理服务 │
│ - AI 生成服务 │
│ - 视频导出服务 │
└─────────────────┬───────────────────────┘
│
┌─────────────────▼───────────────────────┐
│ 数据访问层 (Repositories) │
│ - 数据库操作 │
│ - 缓存操作 │
│ - 文件操作 │
└─────────────────┬───────────────────────┘
│
┌─────────────────▼───────────────────────┐
│ 基础设施层 │
│ - PostgreSQL │
│ - Redis │
│ - 对象存储 │
└─────────────────────────────────────────┘
项目目录结构
backend/
├── app/
│ ├── __init__.py
│ ├── main.py # FastAPI 应用入口
│ ├── config.py # 配置管理
│ │
│ ├── api/ # API 路由
│ │ ├── __init__.py
│ │ ├── v1/
│ │ │ ├── __init__.py
│ │ │ ├── folders.py # 文件夹相关 API
│ │ │ ├── projects.py # 项目相关 API
│ │ │ ├── storyboards.py # 分镜相关 API
│ │ │ ├── resources.py # 资源相关 API
│ │ │ ├── videos.py # 视频相关 API
│ │ │ ├── scripts.py # 剧本相关 API
│ │ │ ├── attachments.py # 附件相关 API
│ │ │ ├── ai.py # AI 生成 API
│ │ │ └── export.py # 导出相关 API
│ │ └── dependencies.py # 依赖注入
│ │
│ ├── core/ # 核心功能
│ │ ├── __init__.py
│ │ ├── security.py # 认证授权
│ │ ├── database.py # 数据库连接
│ │ ├── cache.py # 缓存管理
│ │ ├── storage.py # 文件存储
│ │ └── exceptions.py # 自定义异常
│ │
│ ├── models/ # SQLModel 模型(同时用于 ORM 和 API)
│ │ ├── __init__.py
│ │ ├── folder.py
│ │ ├── project.py
│ │ ├── storyboard.py
│ │ ├── resource.py
│ │ ├── video.py
│ │ ├── script.py
│ │ ├── attachment.py
│ │ └── user.py
│ │
│ ├── schemas/ # 额外的请求/响应模型(可选)
│ │ ├── __init__.py
│ │ ├── common.py # 通用响应模型
│ │ └── requests.py # 特殊请求模型
│ │
│ ├── services/ # 业务逻辑层
│ │ ├── __init__.py
│ │ ├── folder_service.py # 文件夹管理服务
│ │ ├── project_service.py
│ │ ├── storyboard_service.py
│ │ ├── resource_service.py
│ │ ├── video_service.py
│ │ ├── script_service.py # 剧本管理服务
│ │ ├── attachment_service.py # 附件管理服务
│ │ ├── ai_service.py # AI 生成服务
│ │ └── export_service.py # 视频导出服务
│ │
│ ├── repositories/ # 数据访问层
│ │ ├── __init__.py
│ │ ├── folder_repository.py
│ │ ├── project_repository.py
│ │ ├── storyboard_repository.py
│ │ ├── script_repository.py
│ │ ├── attachment_repository.py
│ │ └── base_repository.py
│ │
│ ├── tasks/ # Celery 任务
│ │ ├── __init__.py
│ │ ├── ai_tasks.py # AI 生成任务
│ │ ├── export_tasks.py # 导出任务
│ │ └── celery_app.py # Celery 配置
│ │
│ ├── utils/ # 工具函数
│ │ ├── __init__.py
│ │ ├── file_utils.py
│ │ ├── video_utils.py
│ │ ├── folder_utils.py # 文件夹工具函数
│ │ └── ai_utils.py
│ │
│ └── middleware/ # 中间件
│ ├── __init__.py
│ ├── auth.py
│ └── logging.py
│
├── alembic/ # 数据库迁移
│ ├── versions/
│ └── env.py
│
├── tests/ # 测试
│ ├── __init__.py
│ ├── test_api/
│ ├── test_services/
│ └── conftest.py
│
├── scripts/ # 脚本
│ ├── init_db.py
│ └── seed_data.py
│
├── .env.example # 环境变量示例
├── .gitignore
├── requirements.txt # Python 依赖
├── Dockerfile
├── docker-compose.yml
└── README.md
核心模块设计
1. API 层职责
职责:
- 接收 HTTP 请求
- 参数验证(使用 Pydantic)
- 调用业务逻辑层
- 格式化响应
- 错误处理
示例代码:
# app/api/v1/projects.py
from fastapi import APIRouter, Depends, HTTPException
from sqlmodel import Session
from app.core.database import get_session
from app.core.security import get_current_user
from app.models.project import Project, ProjectCreate
from app.services.project_service import ProjectService
router = APIRouter(prefix="/projects", tags=["projects"])
@router.post("", response_model=Project, status_code=201)
async def create_project(
project_data: ProjectCreate, # SQLModel 自动验证
session: Session = Depends(get_session),
current_user = Depends(get_current_user)
):
"""创建项目"""
service = ProjectService(session)
project = await service.create_project(
user_id=current_user.id,
project_data=project_data
)
return project # SQLModel 自动序列化
2. 业务逻辑层职责
职责:
- 业务规则实现
- 数据验证
- 事务管理
- 调用数据访问层
- 调用外部服务(AI、存储等)
示例代码:
# app/services/project_service.py
from typing import List, Optional
from sqlmodel import Session
from app.models.project import Project, ProjectCreate
from app.repositories.project_repository import ProjectRepository
class ProjectService:
def __init__(self, session: Session):
self.repository = ProjectRepository(session)
self.session = session
async def create_project(
self,
user_id: str,
project_data: ProjectCreate
) -> Project:
"""创建项目"""
# 业务逻辑:检查权限、验证数据等
# SQLModel 支持 .model_dump() 转换为字典
project = Project(
**project_data.model_dump(),
owner_id=user_id
)
return await self.repository.create(project)
3. 数据访问层职责
职责:
- 数据库 CRUD 操作
- 缓存操作
- 查询优化
- 数据转换
示例代码:
# app/repositories/project_repository.py
from typing import List, Optional
from sqlmodel import Session, select
from app.models.project import Project
class ProjectRepository:
def __init__(self, session: Session):
self.session = session
async def create(self, project: Project) -> Project:
"""创建项目"""
self.session.add(project)
await self.session.commit()
await self.session.refresh(project)
return project
async def get_by_id(self, project_id: str) -> Optional[Project]:
"""根据 ID 获取项目"""
statement = select(Project).where(Project.id == project_id)
result = await self.session.exec(statement)
return result.first()
async def get_by_user(
self,
user_id: str,
page: int = 1,
page_size: int = 20
) -> List[Project]:
"""获取用户的项目列表"""
offset = (page - 1) * page_size
statement = select(Project).where(
Project.owner_id == user_id
).offset(offset).limit(page_size)
result = await self.session.exec(statement)
return result.all()
依赖注入
使用 FastAPI 的依赖注入系统管理数据库连接、认证等。
数据库连接
# app/core/database.py
from sqlmodel import create_engine, Session
from app.config import settings
# 创建异步引擎
engine = create_engine(
settings.DATABASE_URL,
echo=True, # 开发环境打印 SQL
pool_pre_ping=True # 连接池健康检查
)
def get_session():
"""获取数据库会话(依赖注入)"""
with Session(engine) as session:
yield session
用户认证
# app/core/security.py
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")
async def get_current_user(token: str = Depends(oauth2_scheme)):
"""获取当前用户"""
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials"
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
user_id: str = payload.get("sub")
if user_id is None:
raise credentials_exception
except JWTError:
raise credentials_exception
# 从数据库获取用户
user = get_user(user_id)
if user is None:
raise credentials_exception
return user
使用依赖注入
# app/api/v1/projects.py
from typing import List
@router.get("", response_model=List[Project])
async def get_projects(
session: Session = Depends(get_session),
current_user = Depends(get_current_user)
):
"""获取项目列表"""
service = ProjectService(session)
projects = await service.get_projects(user_id=current_user.id)
return projects
错误处理
自定义异常
# app/core/exceptions.py
class AppException(Exception):
"""应用基础异常"""
def __init__(self, message: str, status_code: int = 400):
self.message = message
self.status_code = status_code
class NotFoundError(AppException):
"""资源不存在"""
def __init__(self, message: str = "Resource not found"):
super().__init__(message, 404)
class ValidationError(AppException):
"""数据验证错误"""
def __init__(self, message: str):
super().__init__(message, 400)
class PermissionError(AppException):
"""权限错误"""
def __init__(self, message: str = "Permission denied"):
super().__init__(message, 403)
全局异常处理
# app/main.py
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from app.core.exceptions import AppException
app = FastAPI()
@app.exception_handler(AppException)
async def app_exception_handler(request: Request, exc: AppException):
return JSONResponse(
status_code=exc.status_code,
content={"message": exc.message}
)
相关文档
文档版本:v1.0
最后更新:2025-01-27