86 lines
2.7 KiB
Markdown
86 lines
2.7 KiB
Markdown
|
|
# CODEBUDDY.md
|
|||
|
|
|
|||
|
|
此文件为 CodeBuddy Code 在此代码库中工作时提供指导。
|
|||
|
|
|
|||
|
|
## 常用命令
|
|||
|
|
|
|||
|
|
### 应用启动
|
|||
|
|
```bash
|
|||
|
|
# 安装依赖
|
|||
|
|
pip install -r requirements.txt
|
|||
|
|
|
|||
|
|
# 使用便捷启动脚本(推荐)
|
|||
|
|
python start.py --env dev # 开发环境
|
|||
|
|
python start.py --env prod # 生产环境
|
|||
|
|
python start.py --port 9000 # 指定端口
|
|||
|
|
|
|||
|
|
# 直接运行主文件
|
|||
|
|
python main.py
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 环境配置
|
|||
|
|
```bash
|
|||
|
|
# 环境变量优先级(从高到低):
|
|||
|
|
# 1. 环境变量
|
|||
|
|
# 2. .env.{environment} 文件
|
|||
|
|
# 3. .env 基础配置文件
|
|||
|
|
# 4. 代码中的默认值
|
|||
|
|
|
|||
|
|
# 配置验证
|
|||
|
|
python -c "from app.core.config import settings; print(f'Environment: {settings.ENVIRONMENT}'); print(f'Debug: {settings.DEBUG}')"
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
## 架构设计
|
|||
|
|
|
|||
|
|
### 应用工厂模式
|
|||
|
|
项目采用应用工厂模式,核心文件:
|
|||
|
|
- **应用创建**:`app/core/application.py` - 使用 `create_application()` 工厂函数
|
|||
|
|
- **配置管理**:`app/core/config.py` - 基于 pydantic-settings 的多环境配置
|
|||
|
|
- **路由聚合**:`app/api/v1/router.py` - 集中管理 API 路由注册
|
|||
|
|
|
|||
|
|
### 分层架构
|
|||
|
|
1. **API层** (`app/api/v1/endpoints/`) - FastAPI 路由端点,处理 HTTP 请求/响应
|
|||
|
|
2. **服务层** (`app/services/`) - 业务逻辑封装,使用单例服务实例
|
|||
|
|
3. **模型层** (`app/models/`) - 核心领域模型,Pydantic BaseModel
|
|||
|
|
4. **Schema层** (`app/schemas/`) - 请求/响应验证和序列化
|
|||
|
|
|
|||
|
|
### 路由结构
|
|||
|
|
- 所有 API 以 `/api/v1/` 为前缀
|
|||
|
|
- 路由通过 `app/api/v1/router.py` 统一注册
|
|||
|
|
- 每个资源对应一个独立的路由器文件
|
|||
|
|
|
|||
|
|
### 配置管理
|
|||
|
|
- 支持多环境:development、testing、production
|
|||
|
|
- 自动加载对应配置文件:`.env.dev.{env}`
|
|||
|
|
- 类型安全验证和转换
|
|||
|
|
- 便利属性:`settings.is_development`、`settings.is_production`
|
|||
|
|
|
|||
|
|
### 服务模式
|
|||
|
|
- 使用静态服务类 (`UserService`、`ProductService`)
|
|||
|
|
- 当前使用内存数据库进行演示
|
|||
|
|
- 服务层负责所有 CRUD 操作和业务规则
|
|||
|
|
|
|||
|
|
### 关键特性
|
|||
|
|
- CORS 中间件配置
|
|||
|
|
- 应用生命周期事件处理器
|
|||
|
|
- 模块化路由设计
|
|||
|
|
- 版本化的 API 结构
|
|||
|
|
|
|||
|
|
## 开发规范
|
|||
|
|
|
|||
|
|
### 添加新资源
|
|||
|
|
1. 模型层:在 `app/models/` 创建数据模型
|
|||
|
|
2. Schema层:在 `app/schemas/` 创建 Base/Create/Update/Response 模式
|
|||
|
|
3. 服务层:在 `app/services/` 创建服务类
|
|||
|
|
4. API层:在 `app/api/v1/endpoints/` 创建路由端点
|
|||
|
|
5. 路由注册:在 `app/api/v1/router.py` 注册新路由
|
|||
|
|
|
|||
|
|
### 配置扩展
|
|||
|
|
- 新配置项添加到 `app/core/config.py` 中的 Settings 类
|
|||
|
|
- 遵循现有配置验证模式
|
|||
|
|
- 支持环境变量覆盖
|
|||
|
|
|
|||
|
|
### 数据存储
|
|||
|
|
- 当前使用内存数据存储用于演示
|
|||
|
|
- 实际实现将在服务层集成数据库
|
|||
|
|
- 服务接口设计支持无缝替换存储后端
|