# 故障排除指南 ## 当前问题:端口8000被占用 ### 问题描述 运行 `python -m app.main` 或 `python run_server.py` 时,端口8000已经被占用,导致无法访问 http://localhost:8000/docs ### 解决方案 #### 方案1:停止占用端口的进程(推荐) 1. **查看占用端口的进程**: ```powershell netstat -ano | findstr "8000" ``` 2. **停止进程**: ```powershell # 找到PID(例如18712),然后停止它 taskkill /PID 18712 /F ``` 3. **重新启动服务器**: ```powershell python test_server.py ``` #### 方案2:使用不同的端口 1. **修改 `.env` 文件**: ```env PORT=8001 ``` 2. **使用指定端口启动**: ```powershell python test_server_8001.py ``` 3. **访问新地址**: - 主页: http://localhost:8001 - API文档: http://localhost:8001/docs #### 方案3:使用测试服务器 我已经创建了一个简化的测试服务器,可以快速验证功能: ```powershell python test_server.py ``` 如果8000端口被占用,可以使用: ```powershell python test_server_8001.py ``` ### 验证服务器是否正常运行 1. **检查服务器输出**: - 应该看到 "Uvicorn running on http://0.0.0.0:8000" - 没有错误信息 2. **测试根路径**: ```powershell curl http://localhost:8000 ``` 应该返回JSON响应。 3. **访问API文档**: - 打开浏览器访问: http://localhost:8000/docs - 应该看到Swagger UI界面 ### 常见错误 #### 错误1:ModuleNotFoundError: No module named 'app' **原因**:Python路径配置问题 **解决**:使用提供的启动脚本 ```powershell python run_server.py # 或 python test_server.py ``` #### 错误2:Could not parse SQLAlchemy URL from string '' **原因**:环境变量未加载 **解决**: 1. 确保 `.env` 文件存在 2. 检查 `DATABASE_URL` 配置是否正确 3. 运行配置检查: ```powershell python load_env.py ``` #### 错误3:Address already in use **原因**:端口被占用 **解决**:参考上面的方案1或方案2 ### 完整启动流程 1. **停止所有占用8000端口的进程** 2. **检查配置**: ```powershell python load_env.py python check_config.py ``` 3. **启动测试服务器**: ```powershell python test_server.py ``` 4. **验证服务**: - 浏览器访问: http://localhost:8000/docs - 应该看到API文档界面 5. **如果测试服务器正常,启动完整服务器**: ```powershell python run_server.py ``` ### 获取帮助 如果以上方法都无法解决问题,请提供以下信息: 1. 错误信息的完整输出 2. `python load_env.py` 的输出 3. `netstat -ano | findstr "8000"` 的输出 4. Python版本:`python --version` 5. 操作系统版本 --- ## 快速命令参考 ```powershell # 检查端口占用 netstat -ano | findstr "8000" # 停止进程 taskkill /PID <进程ID> /F # 检查配置 python load_env.py python check_config.py # 测试数据库连接 python test_db_connection.py # 初始化数据库 python simple_init_db.py # 启动测试服务器 python test_server.py # 启动完整服务器 python run_server.py # 访问API文档 # 浏览器打开: http://localhost:8000/docs ```