- 从服务器拉取完整代码 - 按框架规范整理项目结构 - 配置 Drone CI 测试环境部署 - 包含后端(FastAPI)、前端(Vue3)、管理端 技术栈: Vue3 + TypeScript + FastAPI + MySQL
522 lines
10 KiB
Markdown
522 lines
10 KiB
Markdown
# 考培练系统后端快速开始指南
|
||
|
||
## 1. 环境准备
|
||
|
||
### 1.1 系统要求
|
||
- Python 3.8+
|
||
- MySQL 8.0+
|
||
- Redis 6.0+
|
||
- Node.js 16+ (用于前端开发)
|
||
- Git
|
||
|
||
### 1.2 推荐开发工具
|
||
- IDE: PyCharm / VSCode with Python插件
|
||
- API测试: Postman / Insomnia
|
||
- 数据库管理: DBeaver / MySQL Workbench
|
||
- Redis管理: RedisInsight
|
||
|
||
## 2. 项目初始化
|
||
|
||
### 2.1 克隆项目
|
||
```bash
|
||
# 克隆项目到本地
|
||
git clone <repository-url> kaopeilian-backend
|
||
cd kaopeilian-backend
|
||
```
|
||
|
||
### 2.2 创建Python虚拟环境
|
||
```bash
|
||
# 创建虚拟环境
|
||
python3 -m venv venv
|
||
|
||
# 激活虚拟环境
|
||
# Linux/Mac:
|
||
source venv/bin/activate
|
||
# Windows:
|
||
venv\Scripts\activate
|
||
|
||
# 升级pip
|
||
pip install --upgrade pip
|
||
```
|
||
|
||
### 2.3 安装依赖
|
||
```bash
|
||
# 安装所有依赖
|
||
pip install -r requirements/dev.txt
|
||
|
||
# 或者分别安装
|
||
pip install -r requirements/base.txt # 基础依赖
|
||
pip install -r requirements/dev.txt # 开发依赖
|
||
```
|
||
|
||
### 2.4 环境配置
|
||
```bash
|
||
# 复制环境变量示例文件
|
||
cp .env.example .env
|
||
|
||
# 编辑.env文件,配置以下关键变量:
|
||
```
|
||
|
||
编辑 `.env` 文件:
|
||
```env
|
||
# 基础配置
|
||
PROJECT_NAME="考培练系统"
|
||
VERSION="1.0.0"
|
||
DEBUG=true
|
||
LOG_LEVEL=INFO
|
||
|
||
# 安全配置
|
||
SECRET_KEY="your-secret-key-here-must-be-at-least-32-chars"
|
||
|
||
# 数据库配置
|
||
DATABASE_URL="mysql+aiomysql://root:password@localhost:3306/kaopeilian"
|
||
|
||
# Redis配置
|
||
REDIS_URL="redis://localhost:6379/0"
|
||
|
||
# Coze平台配置
|
||
COZE_API_BASE="https://api.coze.cn"
|
||
COZE_WORKSPACE_ID="your-workspace-id"
|
||
COZE_API_TOKEN="pat_your_token_here"
|
||
COZE_TRAINING_BOT_ID="your-training-bot-id"
|
||
COZE_CHAT_BOT_ID="your-chat-bot-id"
|
||
|
||
# Dify平台配置
|
||
DIFY_API_BASE="https://api.dify.ai/v1"
|
||
DIFY_API_KEY="app-your-api-key-here"
|
||
DIFY_EXAM_WORKFLOW_ID="workflow_exam_id"
|
||
DIFY_ASSESSMENT_WORKFLOW_ID="workflow_assessment_id"
|
||
DIFY_RECOMMEND_WORKFLOW_ID="workflow_recommend_id"
|
||
|
||
# CORS配置
|
||
CORS_ORIGINS=["http://localhost:5173", "http://localhost:3000"]
|
||
```
|
||
|
||
## 3. 数据库初始化
|
||
|
||
### 3.1 创建数据库
|
||
```sql
|
||
-- 连接到MySQL
|
||
mysql -u root -p
|
||
|
||
-- 创建数据库
|
||
CREATE DATABASE kaopeilian CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||
|
||
-- 创建专用用户(可选)
|
||
CREATE USER 'kaopeilian'@'localhost' IDENTIFIED BY 'your_password';
|
||
GRANT ALL PRIVILEGES ON kaopeilian.* TO 'kaopeilian'@'localhost';
|
||
FLUSH PRIVILEGES;
|
||
```
|
||
|
||
### 3.2 初始化Alembic(数据库迁移)
|
||
```bash
|
||
# 如果还没有初始化过
|
||
alembic init migrations
|
||
|
||
# 编辑 alembic.ini,设置数据库URL
|
||
# sqlalchemy.url = mysql+aiomysql://root:password@localhost:3306/kaopeilian
|
||
```
|
||
|
||
### 3.3 创建初始迁移
|
||
```bash
|
||
# 生成初始迁移文件
|
||
alembic revision --autogenerate -m "initial tables"
|
||
|
||
# 查看生成的迁移文件
|
||
ls migrations/versions/
|
||
|
||
# 应用迁移
|
||
alembic upgrade head
|
||
```
|
||
|
||
### 3.4 创建种子数据(可选)
|
||
```bash
|
||
# 运行种子数据脚本
|
||
python scripts/seed_data.py
|
||
```
|
||
|
||
## 4. 启动服务
|
||
|
||
### 4.1 启动依赖服务
|
||
|
||
使用Docker Compose启动MySQL和Redis:
|
||
```bash
|
||
# 启动依赖服务
|
||
docker-compose up -d mysql redis
|
||
|
||
# 查看服务状态
|
||
docker-compose ps
|
||
|
||
# 查看日志
|
||
docker-compose logs -f mysql
|
||
docker-compose logs -f redis
|
||
```
|
||
|
||
或者手动启动本地服务:
|
||
```bash
|
||
# 启动MySQL
|
||
sudo systemctl start mysql
|
||
# 或
|
||
brew services start mysql # macOS
|
||
|
||
# 启动Redis
|
||
sudo systemctl start redis
|
||
# 或
|
||
brew services start redis # macOS
|
||
```
|
||
|
||
### 4.2 启动开发服务器
|
||
```bash
|
||
# 方式1:使用uvicorn直接启动
|
||
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
|
||
|
||
# 方式2:使用make命令
|
||
make run-dev
|
||
|
||
# 方式3:使用启动脚本
|
||
./scripts/start_dev.sh
|
||
```
|
||
|
||
### 4.3 验证服务启动
|
||
```bash
|
||
# 检查健康状态
|
||
curl http://localhost:8000/health
|
||
|
||
# 查看API文档
|
||
open http://localhost:8000/docs # Swagger UI
|
||
open http://localhost:8000/redoc # ReDoc
|
||
```
|
||
|
||
## 5. 开发工作流
|
||
|
||
### 5.1 创建功能分支
|
||
```bash
|
||
# 基于develop创建功能分支
|
||
git checkout develop
|
||
git pull origin develop
|
||
git checkout -b feature/your-module-name
|
||
|
||
# 例如:
|
||
git checkout -b feature/auth
|
||
git checkout -b feature/user
|
||
git checkout -b feature/course
|
||
```
|
||
|
||
### 5.2 代码开发流程
|
||
```bash
|
||
# 1. 编写代码
|
||
# 2. 格式化代码
|
||
make format
|
||
|
||
# 3. 检查代码质量
|
||
make lint
|
||
|
||
# 4. 类型检查
|
||
make type-check
|
||
|
||
# 5. 运行测试
|
||
make test
|
||
|
||
# 或一次性运行所有检查
|
||
make check-all
|
||
```
|
||
|
||
### 5.3 提交代码
|
||
```bash
|
||
# 添加更改
|
||
git add .
|
||
|
||
# 提交(会自动运行pre-commit hooks)
|
||
git commit -m "feat(auth): 实现用户登录功能"
|
||
|
||
# 推送到远程
|
||
git push origin feature/your-module-name
|
||
```
|
||
|
||
### 5.4 创建Pull Request
|
||
1. 在GitHub/GitLab上创建PR
|
||
2. 填写PR模板
|
||
3. 等待代码审查
|
||
4. 合并到develop分支
|
||
|
||
## 6. 模块开发指南
|
||
|
||
### 6.1 创建新模块的步骤
|
||
|
||
以用户模块为例:
|
||
|
||
1. **创建模型文件**
|
||
```python
|
||
# app/models/user.py
|
||
from sqlalchemy import Column, String, Boolean
|
||
from app.models.base import BaseModel, AuditMixin
|
||
|
||
class User(BaseModel, AuditMixin):
|
||
__tablename__ = "users"
|
||
|
||
username = Column(String(50), unique=True, nullable=False)
|
||
email = Column(String(100), unique=True, nullable=False)
|
||
password_hash = Column(String(200), nullable=False)
|
||
is_active = Column(Boolean, default=True)
|
||
```
|
||
|
||
2. **创建Schema文件**
|
||
```python
|
||
# app/schemas/user.py
|
||
from pydantic import EmailStr, validator
|
||
from app.schemas.base import BaseSchema, TimestampMixin, IDMixin
|
||
|
||
class UserBase(BaseSchema):
|
||
username: str
|
||
email: EmailStr
|
||
|
||
class UserCreate(UserBase):
|
||
password: str
|
||
|
||
@validator('password')
|
||
def validate_password(cls, v):
|
||
# 密码验证逻辑
|
||
return v
|
||
|
||
class UserUpdate(BaseSchema):
|
||
email: Optional[EmailStr] = None
|
||
is_active: Optional[bool] = None
|
||
|
||
class UserInDB(UserBase, IDMixin, TimestampMixin):
|
||
is_active: bool
|
||
```
|
||
|
||
3. **创建服务文件**
|
||
```python
|
||
# app/services/user_service.py
|
||
from app.services.base_service import BaseService
|
||
from app.models.user import User
|
||
from app.schemas.user import UserCreate, UserUpdate
|
||
|
||
class UserService(BaseService[User, UserCreate, UserUpdate]):
|
||
def __init__(self, db):
|
||
super().__init__(User, db)
|
||
|
||
# 添加特定的业务逻辑
|
||
```
|
||
|
||
4. **创建API路由**
|
||
```python
|
||
# app/api/v1/users.py
|
||
from fastapi import APIRouter, Depends
|
||
from app.api.deps import get_db, get_current_user
|
||
from app.services.user_service import UserService
|
||
|
||
router = APIRouter()
|
||
|
||
@router.get("/users")
|
||
async def get_users(
|
||
db = Depends(get_db),
|
||
current_user = Depends(get_current_user)
|
||
):
|
||
service = UserService(db)
|
||
return await service.get_multi()
|
||
```
|
||
|
||
5. **注册路由**
|
||
```python
|
||
# app/api/v1/__init__.py
|
||
from fastapi import APIRouter
|
||
from app.api.v1 import users
|
||
|
||
api_router = APIRouter()
|
||
api_router.include_router(users.router, prefix="/users", tags=["users"])
|
||
```
|
||
|
||
### 6.2 测试开发
|
||
|
||
1. **创建测试文件**
|
||
```python
|
||
# tests/unit/test_user_service.py
|
||
import pytest
|
||
from app.services.user_service import UserService
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_create_user(db_session):
|
||
service = UserService(db_session)
|
||
# 测试逻辑
|
||
```
|
||
|
||
2. **运行测试**
|
||
```bash
|
||
# 运行所有测试
|
||
pytest
|
||
|
||
# 运行特定模块测试
|
||
pytest tests/unit/test_user_service.py
|
||
|
||
# 运行并查看覆盖率
|
||
pytest --cov=app --cov-report=html
|
||
```
|
||
|
||
## 7. 调试技巧
|
||
|
||
### 7.1 使用IPython进行交互式调试
|
||
```bash
|
||
# 安装ipython
|
||
pip install ipython
|
||
|
||
# 在代码中添加断点
|
||
import IPython; IPython.embed()
|
||
```
|
||
|
||
### 7.2 使用VSCode调试
|
||
创建 `.vscode/launch.json`:
|
||
```json
|
||
{
|
||
"version": "0.2.0",
|
||
"configurations": [
|
||
{
|
||
"name": "Python: FastAPI",
|
||
"type": "python",
|
||
"request": "launch",
|
||
"module": "uvicorn",
|
||
"args": [
|
||
"app.main:app",
|
||
"--reload",
|
||
"--host",
|
||
"0.0.0.0",
|
||
"--port",
|
||
"8000"
|
||
],
|
||
"jinja": true,
|
||
"justMyCode": true,
|
||
"env": {
|
||
"PYTHONPATH": "${workspaceFolder}"
|
||
}
|
||
}
|
||
]
|
||
}
|
||
```
|
||
|
||
### 7.3 查看SQL语句
|
||
```python
|
||
# 在.env中设置
|
||
DEBUG=true
|
||
|
||
# 这会在控制台输出所有SQL语句
|
||
```
|
||
|
||
## 8. 常见问题解决
|
||
|
||
### 8.1 数据库连接失败
|
||
```bash
|
||
# 检查MySQL服务状态
|
||
sudo systemctl status mysql
|
||
|
||
# 检查连接
|
||
mysql -h localhost -u root -p
|
||
|
||
# 检查.env中的DATABASE_URL配置
|
||
```
|
||
|
||
### 8.2 依赖冲突
|
||
```bash
|
||
# 清理并重新安装
|
||
pip uninstall -y -r requirements/base.txt
|
||
pip install -r requirements/base.txt
|
||
```
|
||
|
||
### 8.3 迁移失败
|
||
```bash
|
||
# 查看当前迁移状态
|
||
alembic current
|
||
|
||
# 降级到前一个版本
|
||
alembic downgrade -1
|
||
|
||
# 查看迁移历史
|
||
alembic history
|
||
```
|
||
|
||
### 8.4 Redis连接问题
|
||
```bash
|
||
# 测试Redis连接
|
||
redis-cli ping
|
||
|
||
# 检查Redis配置
|
||
redis-cli CONFIG GET bind
|
||
redis-cli CONFIG GET protected-mode
|
||
```
|
||
|
||
## 9. 部署准备
|
||
|
||
### 9.1 生产环境配置
|
||
```bash
|
||
# 使用生产配置
|
||
cp .env.example .env.prod
|
||
|
||
# 编辑生产配置
|
||
# DEBUG=false
|
||
# LOG_LEVEL=WARNING
|
||
```
|
||
|
||
### 9.2 构建Docker镜像
|
||
```bash
|
||
# 构建镜像
|
||
docker build -t kaopeilian-backend:latest .
|
||
|
||
# 运行容器
|
||
docker run -d \
|
||
--name kaopeilian-backend \
|
||
-p 8000:8000 \
|
||
--env-file .env.prod \
|
||
kaopeilian-backend:latest
|
||
```
|
||
|
||
### 9.3 性能优化
|
||
```bash
|
||
# 使用生产服务器
|
||
gunicorn app.main:app \
|
||
-w 4 \
|
||
-k uvicorn.workers.UvicornWorker \
|
||
--bind 0.0.0.0:8000
|
||
```
|
||
|
||
## 10. 团队协作建议
|
||
|
||
### 10.1 代码审查重点
|
||
- API接口是否符合RESTful规范
|
||
- 是否有适当的错误处理
|
||
- 是否有完整的日志记录
|
||
- 测试覆盖率是否达标
|
||
- 是否有安全漏洞
|
||
|
||
### 10.2 文档要求
|
||
- 每个API必须有完整的文档字符串
|
||
- 复杂的业务逻辑需要添加注释
|
||
- 更新README.md中的相关说明
|
||
- 在CHANGELOG.md中记录重要更改
|
||
|
||
### 10.3 沟通机制
|
||
- 每日站会同步进展
|
||
- 使用Issue跟踪问题
|
||
- PR中详细描述更改内容
|
||
- 遇到阻塞及时沟通
|
||
|
||
## 11. 资源链接
|
||
|
||
- [FastAPI官方文档](https://fastapi.tiangolo.com/)
|
||
- [SQLAlchemy文档](https://docs.sqlalchemy.org/)
|
||
- [Alembic文档](https://alembic.sqlalchemy.org/)
|
||
- [Pydantic文档](https://pydantic-docs.helpmanual.io/)
|
||
- [pytest文档](https://docs.pytest.org/)
|
||
- [项目Wiki](项目Wiki链接)
|
||
- [API文档](http://localhost:8000/docs)
|
||
|
||
## 12. 下一步
|
||
|
||
1. 阅读[开发规范文档](./开发规范文档.md)
|
||
2. 查看[模块分工指南](./模块分工指南.md)
|
||
3. 了解[协作机制设计](./协作机制设计.md)
|
||
4. 开始你负责模块的开发!
|
||
|
||
如有任何问题,请在项目Issue中提出或联系技术负责人。
|
||
|
||
祝开发顺利! 🚀
|