Spaces:
Sleeping
Sleeping
| # Flask 重构迁移指南 | |
| ## 📋 概述 | |
| 本项目已从简单的 `http.server` 重构为功能完善的 Flask Web 应用。 | |
| ## 🎯 重构目标 | |
| - ✅ 提供更强大的 API 开发能力 | |
| - ✅ 支持用户会话和状态管理 | |
| - ✅ 集成 OpenSearch 全文搜索 | |
| - ✅ 更好的错误处理和日志记录 | |
| - ✅ 支持生产环境部署 | |
| ## 📁 新增文件 | |
| ### 核心文件 | |
| - `app.py` - Flask 主应用(已重构) | |
| - `app.py.backup` - 原始版本备份 | |
| - `config.py` - 应用配置文件 | |
| - `opensearch_client.py` - OpenSearch 客户端封装 | |
| ### 配置文件 | |
| - `.env.example` - 环境变量配置示例 | |
| - `run_flask.sh` - 启动脚本 | |
| ### 依赖更新 | |
| - `requirements.txt` - 更新了 Flask 相关依赖 | |
| ## 🚀 快速开始 | |
| ### 1. 安装依赖 | |
| ```bash | |
| pip install -r requirements.txt | |
| ``` | |
| ### 2. 配置环境变量(可选) | |
| ```bash | |
| cp .env.example .env | |
| # 编辑 .env 文件,填入实际配置 | |
| ``` | |
| ### 3. 启动应用 | |
| #### 方式一:直接运行(开发环境) | |
| ```bash | |
| python3 app.py | |
| ``` | |
| #### 方式二:使用启动脚本 | |
| ```bash | |
| chmod +x run_flask.sh | |
| ./run_flask.sh | |
| ``` | |
| #### 方式三:使用 Gunicorn(生产环境) | |
| ```bash | |
| gunicorn -w 4 -b 0.0.0.0:7860 --timeout 120 app:app | |
| ``` | |
| ## 🔌 新增 API 端点 | |
| ### 健康检查 | |
| ``` | |
| GET /api/health | |
| 返回: {"status": "healthy", "timestamp": "...", "version": "2.0.0-flask"} | |
| ``` | |
| ### 书籍信息 | |
| ``` | |
| GET /api/book/info | |
| 返回: {"total_pages": 100, "title": "...", "loaded": true} | |
| ``` | |
| ### 页面内容 | |
| ``` | |
| GET /api/book/page/<page_num> | |
| 返回: {"page_num": 1, "content": {...}, "total_pages": 100} | |
| ``` | |
| ### 保存学习进度 | |
| ``` | |
| POST /api/progress/save | |
| 请求体: { | |
| "current_page": 5, | |
| "bookmarks": [1, 3, 5], | |
| "settings": {...} | |
| } | |
| 返回: {"success": true, "message": "学习进度已保存"} | |
| ``` | |
| ### 加载学习进度 | |
| ``` | |
| GET /api/progress/load | |
| 返回: { | |
| "current_page": 5, | |
| "bookmarks": [1, 3, 5], | |
| "settings": {...} | |
| } | |
| ``` | |
| ### 搜索内容 | |
| ``` | |
| POST /api/search | |
| 请求体: {"keyword": "hello"} | |
| 返回: { | |
| "keyword": "hello", | |
| "total": 10, | |
| "results": [...] | |
| } | |
| ``` | |
| ### OpenSearch 状态 | |
| ``` | |
| GET /api/opensearch/status | |
| 返回: { | |
| "configured": true, | |
| "host": "192.168.3.33", | |
| "port": 9200, | |
| "status": "connected" | |
| } | |
| ``` | |
| ### 学习统计 | |
| ``` | |
| GET /api/stats | |
| 返回: { | |
| "current_page": 5, | |
| "total_bookmarks": 3, | |
| "last_visit": "...", | |
| "total_pages": 100 | |
| } | |
| ``` | |
| ## 🔍 OpenSearch 集成 | |
| ### 初始化客户端 | |
| ```python | |
| from opensearch_client import OpenSearchClient | |
| client = OpenSearchClient( | |
| host='192.168.3.33', | |
| port=9200, | |
| use_ssl=False | |
| ) | |
| # 检查连接 | |
| if client.is_connected(): | |
| print("OpenSearch 连接成功") | |
| ``` | |
| ### 索引文档 | |
| ```python | |
| from opensearch_client import initialize_learning_index | |
| # 初始化索引 | |
| initialize_learning_index(client) | |
| # 索引单词 | |
| doc = { | |
| 'type': 'word', | |
| 'page_num': 1, | |
| 'english': 'hello', | |
| 'chinese': '你好', | |
| 'difficulty': 1, | |
| 'tags': ['greeting', 'basic'] | |
| } | |
| client.index_document('english_learning_content', 'word_hello', doc) | |
| ``` | |
| ### 搜索内容 | |
| ```python | |
| from opensearch_client import search_english_content | |
| results = search_english_content(client, 'hello') | |
| for result in results: | |
| print(f"{result['source']['english']}: {result['source']['chinese']}") | |
| ``` | |
| ## 🛠️ 开发功能 | |
| ### 热重载 | |
| 开发模式下,Flask 会自动检测代码变化并重新加载: | |
| ```bash | |
| export FLASK_DEBUG=True | |
| python3 app.py | |
| ``` | |
| ### 日志记录 | |
| 应用日志会自动保存到 `logs/app.log`: | |
| ```python | |
| from flask import current_app | |
| current_app.logger.info('用户访问了第5页') | |
| current_app.logger.error('发生错误') | |
| ``` | |
| ### 调试模式 | |
| 在开发环境中启用调试模式会显示详细的错误堆栈信息。 | |
| ## 📦 生产环境部署 | |
| ### 使用 Gunicorn | |
| ```bash | |
| # 4个工作进程 | |
| gunicorn -w 4 -b 0.0.0.0:7860 --timeout 120 \ | |
| --access-logfile - --error-logfile - \ | |
| app:app | |
| ``` | |
| ### Docker 部署 | |
| 在 `Dockerfile` 中更新启动命令: | |
| ```dockerfile | |
| CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:7860", "--timeout", "120", "app:app"] | |
| ``` | |
| ### 环境变量 | |
| 生产环境必须设置的环境变量: | |
| ```bash | |
| export SECRET_KEY="your-production-secret-key" | |
| export FLASK_ENV=production | |
| export FLASK_DEBUG=False | |
| ``` | |
| ## 🔒 安全建议 | |
| 1. **SECRET_KEY**: 生产环境必须使用强随机密钥 | |
| 2. **CORS**: 根据需要限制允许的源 | |
| 3. **HTTPS**: 生产环境使用 HTTPS | |
| 4. **环境变量**: 敏感信息不要硬编码 | |
| 5. **日志**: 不要记录敏感数据 | |
| ## 🧪 测试 | |
| ### 测试健康检查 | |
| ```bash | |
| curl http://localhost:7860/api/health | |
| ``` | |
| ### 测试书籍信息 | |
| ```bash | |
| curl http://localhost:7860/api/book/info | |
| ``` | |
| ### 测试搜索 | |
| ```bash | |
| curl -X POST http://localhost:7860/api/search \ | |
| -H "Content-Type: application/json" \ | |
| -d '{"keyword": "hello"}' | |
| ``` | |
| ## 📝 与原版本对比 | |
| | 功能 | 原版本 (http.server) | Flask 版本 | | |
| |------|---------------------|-----------| | |
| | 静态文件服务 | ✅ | ✅ | | |
| | API 端点 | ❌ | ✅ | | |
| | 会话管理 | ❌ | ✅ | | |
| | 日志记录 | 基础 | 完善 | | |
| | 错误处理 | 基础 | 完善 | | |
| | 数据库集成 | ❌ | ✅ (可选) | | |
| | 搜索功能 | ❌ | ✅ (OpenSearch) | | |
| | 生产环境支持 | ❌ | ✅ (Gunicorn) | | |
| | 热重载 | ❌ | ✅ (开发模式) | | |
| ## 🔄 回滚到原版本 | |
| 如果需要回滚到原始版本: | |
| ```bash | |
| cp app.py.backup app.py | |
| python3 app.py | |
| ``` | |
| ## 📚 扩展功能建议 | |
| ### 1. 用户认证 | |
| 安装 Flask-Login 实现用户登录系统 | |
| ### 2. 数据库持久化 | |
| 使用 Flask-SQLAlchemy 存储学习进度 | |
| ### 3. 缓存 | |
| 使用 Flask-Caching 提高性能 | |
| ### 4. API 限流 | |
| 使用 Flask-Limiter 防止滥用 | |
| ### 5. WebSocket | |
| 使用 Flask-SocketIO 实现实时功能 | |
| ## 🆘 常见问题 | |
| ### Q: 启动失败,提示端口被占用? | |
| ```bash | |
| # 查找占用端口的进程 | |
| lsof -i :7860 | |
| # 或使用项目自带的脚本 | |
| ./kill_port.sh 7860 | |
| ``` | |
| ### Q: OpenSearch 连接失败? | |
| 检查配置文件中的 OpenSearch 地址和端口是否正确。 | |
| ### Q: 静态文件无法访问? | |
| 确保 `static/` 目录存在且包含所需的 CSS、JS 文件。 | |
| ## 📞 技术支持 | |
| - 查看日志文件: `logs/app.log` | |
| - 调试模式: 设置 `FLASK_DEBUG=True` | |
| - 查看端口管理文档: `PORT_MANAGEMENT.md` | |
| --- | |
| **重构完成时间**: 2025-10-16 | |
| **Python 版本**: 3.12 | |
| **Flask 版本**: 3.0.0 | |