2026-03-17 13:17:02 +08:00

13 KiB
Raw Permalink Blame History

开发环境搭建指南

本文档详细说明如何在本地环境中搭建QY LTY Backend开发环境。

1. 系统要求

1.1 硬件要求

  • CPU: 2核心及以上
  • 内存: 8GB RAM 最小16GB RAM 推荐
  • 存储: 10GB 可用空间
  • 网络: 稳定的互联网连接(用于下载依赖和访问云服务)

1.2 操作系统支持

  • macOS: 10.15+ (推荐 macOS 12+)
  • Linux: Ubuntu 18.04+, CentOS 7+, 或其他主流发行版
  • Windows: Windows 10+ (建议使用 WSL2)

1.3 软件依赖

  • Python: 3.9+
  • Node.js: 16+ (用于前端工具,可选)
  • Git: 2.20+

2. 环境准备

2.1 安装 Anaconda/Miniconda

macOS 和 Linux:

# 下载 Miniconda
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
# 或者 macOS:
# wget https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-x86_64.sh

# 安装
bash Miniconda3-latest-Linux-x86_64.sh

# 重启终端或执行
source ~/.bashrc

Windows:

  1. 下载 Miniconda Windows 安装包
  2. 运行安装程序,按照提示完成安装
  3. 打开 Anaconda Prompt

2.2 创建项目专用Conda环境

# 创建名为lty的conda环境
conda create -n lty python=3.9

# 激活环境
conda activate lty

# 验证Python版本
python --version  # 应该显示 Python 3.9.x

2.3 安装系统级依赖

macOS:

# 使用 Homebrew 安装
brew install postgresql redis

# 启动服务
brew services start postgresql
brew services start redis

Ubuntu/Debian:

# 安装 PostgreSQL
sudo apt update
sudo apt install postgresql postgresql-contrib

# 安装 Redis
sudo apt install redis-server

# 启动服务
sudo systemctl start postgresql
sudo systemctl start redis-server
sudo systemctl enable postgresql
sudo systemctl enable redis-server

CentOS/RHEL:

# 安装 PostgreSQL
sudo yum install postgresql-server postgresql-contrib
sudo postgresql-setup initdb

# 安装 Redis
sudo yum install redis

# 启动服务
sudo systemctl start postgresql
sudo systemctl start redis
sudo systemctl enable postgresql
sudo systemctl enable redis

3. 项目设置

3.1 克隆项目代码

# 克隆代码库
git clone https://github.com/your-org/qy_ai_backend.git
cd qy_ai_backend

# 查看分支
git branch -a

# 切换到开发分支(如果有)
git checkout develop

3.2 安装Python依赖

# 确保在lty环境中
conda activate lty

# 安装项目依赖
pip install -r requirements.txt

# 验证关键包安装
python -c "import django; print(django.get_version())"
python -c "import channels; print('Channels installed')"

3.3 环境变量配置

# 复制环境变量模板
cp .env.bak .env

# 编辑环境变量文件
nano .env  # 或使用你喜欢的编辑器

必须配置的环境变量:

# Django 核心配置
SECRET_KEY=your-secret-key-here
DEBUG=True

# 数据库配置
POSTGRESQL_DATABASE_NAME=qy_lty_dev
POSTGRESQL_DATABASE_USER=your_username
POSTGRESQL_DATABASE_PASSWORD=your_password
POSTGRESQL_DATABASE_HOST=localhost
POSTGRESQL_DATABASE_PORT=5432

# Redis 配置
REDIS_LOCATION=redis://127.0.0.1:6379/1
REDIS_PASSWORD=

# AI服务配置
KIMI_API_KEY=your-kimi-api-key
KIMI_BASE_URL=https://api.moonshot.cn/v1

# 阿里云服务配置(可选,用于短信验证等)
ALIYUN_SMS_ACCESS_KEY_ID=your-access-key-id
ALIYUN_SMS_ACCESS_KEY_SECRET=your-access-key-secret
ALIYUN_SMS_SIGN_NAME=your-sms-sign
ALIYUN_SMS_TEMPLATE_CODE=your-template-code

# 其他服务配置
VOLCENGINE_ACCESS_KEY=your-volcengine-key
VOLCENGINE_SECRET_KEY=your-volcengine-secret
AUDIO_SERVICE_PROVIDER=huoshan

4. 数据库设置

4.1 PostgreSQL 数据库配置

# 连接到 PostgreSQL
sudo -u postgres psql

# 在 PostgreSQL 命令行中执行:
CREATE DATABASE qy_lty_dev;
CREATE USER your_username WITH PASSWORD 'your_password';
GRANT ALL PRIVILEGES ON DATABASE qy_lty_dev TO your_username;

# 退出 PostgreSQL
\q

4.2 运行数据库迁移

# 确保在项目根目录和lty环境中
conda activate lty
cd /path/to/qy_ai_backend

# 生成迁移文件(如果需要)
python manage.py makemigrations

# 执行迁移
python manage.py migrate

# 验证迁移结果
python manage.py showmigrations

4.3 创建超级用户

# 创建Django管理员账户
python manage.py createsuperuser

# 按提示输入用户名、邮箱和密码

5. Redis 配置验证

# 测试 Redis 连接
redis-cli ping
# 应该返回 PONG

# 测试 Django Redis 缓存
python manage.py shell
>>> from django.core.cache import cache
>>> cache.set('test', 'hello')
>>> cache.get('test')
# 应该返回 'hello'
>>> exit()

6. 启动开发服务器

6.1 基础启动方式

# 方式1: 使用项目提供的脚本
chmod +x run.sh
./run.sh

# 方式2: 使用 daphne (推荐支持WebSocket)
daphne -b 0.0.0.0 -p 8000 qy_lty.asgi:application

# 方式3: 使用传统Django开发服务器不支持WebSocket
python manage.py runserver

6.2 验证服务启动

访问以下URL验证服务是否正常启动

7. 开发工具配置

7.1 IDE配置推荐

VS Code 插件推荐:

{
  "recommendations": [
    "ms-python.python",
    "ms-python.django",
    "ms-vscode.vscode-json",
    "redhat.vscode-yaml",
    "ms-python.flake8",
    "ms-python.black-formatter",
    "bradlc.vscode-tailwindcss"
  ]
}

PyCharm 配置:

  1. 设置Python解释器为conda环境中的Python
  2. 配置Django项目设置
  3. 设置代码格式化工具

7.2 Git 钩子设置

# 安装 pre-commit可选
pip install pre-commit

# 如果项目有 .pre-commit-config.yaml安装钩子
pre-commit install

7.3 调试配置

VS Code launch.json 示例:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Django",
      "type": "python",
      "request": "launch",
      "program": "${workspaceFolder}/manage.py",
      "args": [
        "runserver",
        "8000"
      ],
      "django": true,
      "justMyCode": true
    },
    {
      "name": "Django Daphne",
      "type": "python",
      "request": "launch",
      "module": "daphne",
      "args": [
        "-b", "0.0.0.0",
        "-p", "8000",
        "qy_lty.asgi:application"
      ],
      "django": true,
      "justMyCode": true
    }
  ]
}

8. 测试环境验证

8.1 运行单元测试

# 运行所有测试
python manage.py test

# 运行特定应用的测试
python manage.py test userapp
python manage.py test aiapp

# 运行时显示详细信息
python manage.py test --verbosity=2

8.2 API测试

# 使用 curl 测试API
curl -X GET http://localhost:8000/api/user/auth/user/ \
  -H "Authorization: Bearer your-token-here"

# 或使用 httpie需要安装pip install httpie
http GET localhost:8000/api/user/auth/user/ \
  Authorization:"Bearer your-token-here"

8.3 WebSocket测试

# 安装WebSocket测试工具
pip install websockets

# 创建测试脚本
cat > test_websocket.py << 'EOF'
import asyncio
import websockets
import json

async def test_websocket():
    uri = "ws://localhost:8000/ws/device/"
    async with websockets.connect(uri) as websocket:
        # 发送测试消息
        message = {
            "type": "chat_message",
            "message": "Hello WebSocket",
            "user_id": "1"
        }
        await websocket.send(json.dumps(message))
        
        # 接收响应
        response = await websocket.recv()
        print(f"收到响应: {response}")

asyncio.run(test_websocket())
EOF

# 运行测试
python test_websocket.py

9. 常见问题排查

9.1 数据库连接问题

错误: django.db.utils.OperationalError: FATAL: password authentication failed

解决方案:

# 检查PostgreSQL服务状态
sudo systemctl status postgresql

# 重置用户密码
sudo -u postgres psql
ALTER USER your_username WITH PASSWORD 'new_password';
\q

# 更新.env文件中的密码

9.2 Redis连接问题

错误: redis.exceptions.ConnectionError: Error 111 connecting to 127.0.0.1:6379

解决方案:

# 检查Redis服务状态
redis-cli ping

# 如果服务未启动
sudo systemctl start redis-server

# 检查Redis配置
sudo nano /etc/redis/redis.conf

9.3 依赖包安装问题

错误: error: Microsoft Visual C++ 14.0 is required (Windows)

解决方案:

# Windows: 安装 Visual Studio Build Tools
# 或者使用conda安装问题包
conda install package_name

# Linux: 安装编译工具
sudo apt install build-essential python3-dev

9.4 端口占用问题

错误: Error: That port is already in use

解决方案:

# 查找占用端口的进程
lsof -i :8000

# 杀死进程
kill -9 PID

# 或使用不同端口
python manage.py runserver 8001

10. 开发环境优化

10.1 性能优化

# 安装开发版本的依赖
pip install django-debug-toolbar
pip install django-extensions

# 在settings.py中启用调试工具已配置

10.2 数据库性能

# 为开发环境创建数据库索引
python manage.py dbshell
# 在数据库中执行必要的索引创建语句

10.3 缓存配置

# 清空Redis缓存
redis-cli FLUSHALL

# 验证缓存配置
python manage.py shell
>>> from django.core.cache import cache
>>> cache.clear()

11. 团队开发规范

11.1 代码格式化

# 安装代码格式化工具
pip install black flake8 isort

# 格式化代码
black .
isort .
flake8 .

11.2 提交规范

# 提交信息格式
git commit -m "type(scope): description

[optional body]

[optional footer]"

# 示例
git commit -m "feat(userapp): add phone login functionality

- Add PhoneLoginView for SMS verification
- Update user model to include phone field
- Add Aliyun SMS integration

Closes #123"

11.3 分支管理

# 功能开发分支
git checkout -b feature/user-phone-login

# 修复分支
git checkout -b hotfix/auth-token-expire

# 合并到主分支前进行代码审查
git push origin feature/user-phone-login
# 创建Pull Request

12. 环境变量参考

12.1 完整环境变量示例

# Django核心配置
SECRET_KEY=django-insecure-your-secret-key-for-development-only
DEBUG=True

# 数据库配置
POSTGRESQL_DATABASE_NAME=qy_lty_dev
POSTGRESQL_DATABASE_USER=qy_dev_user
POSTGRESQL_DATABASE_PASSWORD=dev_password_123
POSTGRESQL_DATABASE_HOST=localhost
POSTGRESQL_DATABASE_PORT=5432

# Redis配置
REDIS_LOCATION=redis://127.0.0.1:6379/1
REDIS_PASSWORD=

# AI服务配置
KIMI_API_KEY=sk-your-kimi-api-key-here
KIMI_BASE_URL=https://api.moonshot.cn/v1

# 阿里云配置
ALIYUN_SMS_ACCESS_KEY_ID=your-aliyun-access-key-id
ALIYUN_SMS_ACCESS_KEY_SECRET=your-aliyun-access-key-secret
ALIYUN_SMS_SIGN_NAME=您的签名
ALIYUN_SMS_TEMPLATE_CODE=SMS_123456789

ALIYUN_OSS_ACCESS_KEY_ID=your-oss-key-id
ALIYUN_OSS_ACCESS_KEY_SECRET=your-oss-key-secret
ALIYUN_OSS_BUCKET=your-bucket-name
ALIYUN_OSS_ENDPOINT=oss-cn-beijing.aliyuncs.com
ALIYUN_OSS_HOST=https://your-bucket.oss-cn-beijing.aliyuncs.com
ALIYUN_OSS_AUDIO_BASE_DIR=audio/

# 火山引擎配置
VOLCENGINE_ACCESS_KEY=your-volcengine-access-key
VOLCENGINE_SECRET_KEY=your-volcengine-secret-key
VOLCENGINE_APP_ID=your-volcengine-app-id
VOLCENGINE_APP_KEY=your-volcengine-app-key

# 音频服务配置
AUDIO_SERVICE_PROVIDER=huoshan
AUDIO_SERVICE_HUOSHAN_APPID=your-huoshan-appid
AUDIO_SERVICE_HUOSHAN_ACCESS_TOKEN=your-huoshan-token
AUDIO_SERVICE_HUOSHAN_CLUSTER=volcano_tts
AUDIO_SERVICE_HUOSHAN_VOICE_TYPE=BV001_streaming
AUDIO_SERVICE_HUOSHAN_STORAGE_DIR=/tmp/audio/
AUDIO_SERVICE_HUOSHAN_BASE_URL=https://openspeech.bytedance.com

# 阿里云语音识别用于火山引擎服务的ASR
ALIYUN_NLS_ACCESS_KEY_ID=your-nls-key-id
ALIYUN_NLS_ACCESS_KEY_SECRET=your-nls-key-secret
ALIYUN_NLS_APP_ID=your-nls-app-id

12.2 生产环境变量

# 生产环境请务必修改以下配置
DEBUG=False
SECRET_KEY=your-production-secret-key-very-long-and-random

# 使用强密码和安全配置
POSTGRESQL_DATABASE_PASSWORD=very-strong-production-password
REDIS_PASSWORD=redis-strong-password

# 配置HTTPS和域名
ALLOWED_HOSTS=yourdomain.com,www.yourdomain.com
CORS_ALLOWED_ORIGINS=https://yourdomain.com,https://www.yourdomain.com

这样就完成了完整的开发环境搭建指南。开发者可以按照这个文档逐步搭建本地开发环境。