315 lines
5.5 KiB
Markdown
315 lines
5.5 KiB
Markdown
# 开发指南
|
||
|
||
## 快速开始
|
||
|
||
### 本地开发
|
||
|
||
```bash
|
||
# 1. 进入后端目录
|
||
cd /vol1/1000/docker_server/traefik/web/ws/backend
|
||
|
||
# 2. 使用启动脚本(自动创建虚拟环境、安装依赖)
|
||
./start.sh
|
||
|
||
# 或者手动启动
|
||
python3 -m venv venv
|
||
source venv/bin/activate
|
||
pip install -r requirements.txt
|
||
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
|
||
```
|
||
|
||
访问:
|
||
- API 文档: http://localhost:8000/docs
|
||
- 健康检查: http://localhost:8000/health
|
||
|
||
### Docker 开发
|
||
|
||
```bash
|
||
cd /vol1/1000/docker_server/traefik/web/ws
|
||
|
||
# 构建镜像
|
||
docker compose build backend
|
||
|
||
# 启动服务
|
||
docker compose up -d backend
|
||
|
||
# 查看日志
|
||
docker compose logs -f backend
|
||
|
||
# 进入容器
|
||
docker compose exec backend bash
|
||
```
|
||
|
||
## 开发流程
|
||
|
||
### 1. 添加新的 API 端点
|
||
|
||
**示例:添加实验数据 API**
|
||
|
||
```bash
|
||
# 1. 创建端点文件
|
||
touch app/api/v1/endpoints/experiments.py
|
||
```
|
||
|
||
```python
|
||
# app/api/v1/endpoints/experiments.py
|
||
from fastapi import APIRouter
|
||
|
||
router = APIRouter()
|
||
|
||
@router.get("/")
|
||
async def get_experiments():
|
||
"""获取实验列表"""
|
||
return {"experiments": []}
|
||
|
||
@router.get("/{experiment_id}")
|
||
async def get_experiment(experiment_id: str):
|
||
"""获取实验详情"""
|
||
return {"id": experiment_id}
|
||
```
|
||
|
||
```python
|
||
# 2. 在 app/api/v1/router.py 中注册
|
||
from app.api.v1.endpoints import experiments
|
||
|
||
api_router.include_router(
|
||
experiments.router,
|
||
prefix="/experiments",
|
||
tags=["experiments"]
|
||
)
|
||
```
|
||
|
||
### 2. 添加数据模型
|
||
|
||
```bash
|
||
# 创建模型文件
|
||
touch app/models/experiment.py
|
||
```
|
||
|
||
```python
|
||
# app/models/experiment.py
|
||
from sqlalchemy import Column, String, Integer, DateTime
|
||
from sqlalchemy.ext.declarative import declarative_base
|
||
|
||
Base = declarative_base()
|
||
|
||
class Experiment(Base):
|
||
__tablename__ = "experiments"
|
||
|
||
id = Column(Integer, primary_key=True)
|
||
name = Column(String(200))
|
||
description = Column(String(1000))
|
||
created_at = Column(DateTime)
|
||
```
|
||
|
||
### 3. 添加 Pydantic 模式
|
||
|
||
```bash
|
||
# 创建模式文件
|
||
touch app/schemas/experiment.py
|
||
```
|
||
|
||
```python
|
||
# app/schemas/experiment.py
|
||
from pydantic import BaseModel
|
||
from datetime import datetime
|
||
from typing import Optional
|
||
|
||
class ExperimentBase(BaseModel):
|
||
name: str
|
||
description: Optional[str] = None
|
||
|
||
class ExperimentCreate(ExperimentBase):
|
||
pass
|
||
|
||
class ExperimentResponse(ExperimentBase):
|
||
id: int
|
||
created_at: datetime
|
||
|
||
class Config:
|
||
from_attributes = True
|
||
```
|
||
|
||
### 4. 添加业务逻辑
|
||
|
||
```bash
|
||
# 创建服务文件
|
||
touch app/services/experiment_service.py
|
||
```
|
||
|
||
```python
|
||
# app/services/experiment_service.py
|
||
from sqlalchemy.orm import Session
|
||
from app.models.experiment import Experiment
|
||
from app.schemas.experiment import ExperimentCreate
|
||
|
||
async def create_experiment(db: Session, data: ExperimentCreate):
|
||
"""创建实验"""
|
||
experiment = Experiment(**data.dict())
|
||
db.add(experiment)
|
||
db.commit()
|
||
db.refresh(experiment)
|
||
return experiment
|
||
```
|
||
|
||
## 代码规范
|
||
|
||
### Python 风格
|
||
|
||
- 遵循 PEP 8 规范
|
||
- 使用类型提示
|
||
- 函数添加文档字符串
|
||
|
||
```python
|
||
async def get_strain_detail(strain_id: str) -> dict:
|
||
"""
|
||
获取菌种详情
|
||
|
||
Args:
|
||
strain_id: 菌种 ID
|
||
|
||
Returns:
|
||
dict: 菌种详细信息
|
||
|
||
Raises:
|
||
HTTPException: 菌种不存在时
|
||
"""
|
||
pass
|
||
```
|
||
|
||
### 命名规范
|
||
|
||
- 文件名:`snake_case.py`
|
||
- 类名:`PascalCase`
|
||
- 函数名:`snake_case`
|
||
- 常量:`UPPER_CASE`
|
||
|
||
### 目录组织
|
||
|
||
```
|
||
app/
|
||
├── api/v1/endpoints/ # 按功能模块组织
|
||
│ ├── strains.py # 菌种相关
|
||
│ ├── genes.py # 基因相关
|
||
│ └── upload.py # 上传相关
|
||
├── models/ # 数据库模型
|
||
├── schemas/ # 数据验证模式
|
||
└── services/ # 业务逻辑
|
||
```
|
||
|
||
## 测试
|
||
|
||
### 单元测试
|
||
|
||
```bash
|
||
# 安装测试依赖
|
||
pip install pytest pytest-asyncio httpx
|
||
|
||
# 运行测试
|
||
pytest
|
||
```
|
||
|
||
### API 测试
|
||
|
||
```bash
|
||
# 使用测试脚本
|
||
./test_api.sh
|
||
|
||
# 或使用 curl
|
||
curl http://localhost:8000/health
|
||
```
|
||
|
||
## 数据库迁移
|
||
|
||
```bash
|
||
# 安装 alembic
|
||
pip install alembic
|
||
|
||
# 初始化
|
||
alembic init alembic
|
||
|
||
# 创建迁移
|
||
alembic revision --autogenerate -m "Add experiments table"
|
||
|
||
# 执行迁移
|
||
alembic upgrade head
|
||
|
||
# 回滚
|
||
alembic downgrade -1
|
||
```
|
||
|
||
## 调试技巧
|
||
|
||
### 1. 日志输出
|
||
|
||
```python
|
||
import logging
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
@router.get("/debug")
|
||
async def debug_endpoint():
|
||
logger.info("Debug endpoint called")
|
||
logger.debug(f"Data: {data}")
|
||
return {"status": "ok"}
|
||
```
|
||
|
||
### 2. 断点调试
|
||
|
||
```python
|
||
# 使用 pdb
|
||
import pdb; pdb.set_trace()
|
||
|
||
# 或使用 breakpoint()
|
||
breakpoint()
|
||
```
|
||
|
||
### 3. 查看 SQL 查询
|
||
|
||
```python
|
||
# 在配置中启用 SQL 日志
|
||
DATABASE_URL = "postgresql://...?echo=true"
|
||
```
|
||
|
||
## 常见问题
|
||
|
||
### Q: 导入错误?
|
||
|
||
确保在项目根目录运行,并使用正确的 Python 路径:
|
||
|
||
```bash
|
||
export PYTHONPATH=/vol1/1000/docker_server/traefik/web/ws/backend:$PYTHONPATH
|
||
```
|
||
|
||
### Q: 数据库连接失败?
|
||
|
||
检查 `.env` 文件中的 `DATABASE_URL` 配置。
|
||
|
||
### Q: CORS 错误?
|
||
|
||
在 `app/core/config.py` 中添加允许的源。
|
||
|
||
## 部署检查清单
|
||
|
||
- [ ] 修改生产环境 `SECRET_KEY`
|
||
- [ ] 配置正确的 `DATABASE_URL`
|
||
- [ ] 更新 `ALLOWED_ORIGINS`
|
||
- [ ] 运行数据库迁移
|
||
- [ ] 测试所有 API 端点
|
||
- [ ] 配置日志记录
|
||
- [ ] 设置监控和告警
|
||
- [ ] 备份数据库
|
||
|
||
## 贡献流程
|
||
|
||
1. 创建功能分支
|
||
2. 开发并测试
|
||
3. 提交代码(commit message 规范)
|
||
4. 提交 Pull Request
|
||
5. Code Review
|
||
6. 合并到主分支
|
||
|
||
## 联系方式
|
||
|
||
如有问题,请联系开发团队。
|