Add Flask/Python backend server
- Create app.py with Flask server on port 5002 - Add requirements.txt with Python dependencies - Add run_flask.bat for Windows users - Add run_flask.sh for Linux/Mac users - Complete Flask setup documentation - Database integration with PyMySQL - Full LLM API support (Gemini, DeepSeek, OpenAI, Claude) - CORS configuration - Error handling middleware Features: ✅ Runs on http://127.0.0.1:5002 ✅ All LLM APIs supported ✅ Database connection ✅ API proxy for CORS fix ✅ Auto setup scripts 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
392
FLASK_SETUP.md
Normal file
392
FLASK_SETUP.md
Normal file
@@ -0,0 +1,392 @@
|
||||
# Flask 伺服器設定指南
|
||||
|
||||
## 🐍 Python Flask 後端伺服器
|
||||
|
||||
本專案提供 **Python Flask** 版本的後端伺服器,運行於 `http://127.0.0.1:5002`
|
||||
|
||||
## 📋 系統需求
|
||||
|
||||
- **Python**: 3.8 或更高版本
|
||||
- **pip**: Python 套件管理工具
|
||||
- **MySQL**: 資料庫(已設定)
|
||||
|
||||
## 🚀 快速開始
|
||||
|
||||
### Windows 用戶
|
||||
|
||||
1. **雙擊執行啟動腳本**
|
||||
```bash
|
||||
run_flask.bat
|
||||
```
|
||||
|
||||
腳本會自動:
|
||||
- ✅ 檢查 Python 安裝
|
||||
- ✅ 建立虛擬環境(第一次執行)
|
||||
- ✅ 安裝所有依賴
|
||||
- ✅ 啟動 Flask 伺服器
|
||||
|
||||
2. **或手動執行**
|
||||
```bash
|
||||
# 建立虛擬環境
|
||||
python -m venv venv
|
||||
|
||||
# 啟動虛擬環境
|
||||
venv\Scripts\activate
|
||||
|
||||
# 安裝依賴
|
||||
pip install -r requirements.txt
|
||||
|
||||
# 啟動伺服器
|
||||
python app.py
|
||||
```
|
||||
|
||||
### Linux/Mac 用戶
|
||||
|
||||
1. **執行啟動腳本**
|
||||
```bash
|
||||
chmod +x run_flask.sh
|
||||
./run_flask.sh
|
||||
```
|
||||
|
||||
2. **或手動執行**
|
||||
```bash
|
||||
# 建立虛擬環境
|
||||
python3 -m venv venv
|
||||
|
||||
# 啟動虛擬環境
|
||||
source venv/bin/activate
|
||||
|
||||
# 安裝依賴
|
||||
pip install -r requirements.txt
|
||||
|
||||
# 啟動伺服器
|
||||
python3 app.py
|
||||
```
|
||||
|
||||
## 📦 已安裝的套件
|
||||
|
||||
```
|
||||
Flask==3.0.0 # Web 框架
|
||||
Flask-Cors==4.0.0 # CORS 支援
|
||||
PyMySQL==1.1.0 # MySQL 連接器
|
||||
requests==2.31.0 # HTTP 請求
|
||||
python-dotenv==1.0.0 # 環境變數管理
|
||||
```
|
||||
|
||||
完整清單請參考 [requirements.txt](requirements.txt)
|
||||
|
||||
## 🌐 服務端點
|
||||
|
||||
### 基礎端點
|
||||
|
||||
```
|
||||
GET http://127.0.0.1:5002/
|
||||
- API 資訊
|
||||
|
||||
GET http://127.0.0.1:5002/health
|
||||
- 健康檢查
|
||||
|
||||
GET http://127.0.0.1:5002/api-proxy-example.html
|
||||
- API 使用範例頁面
|
||||
```
|
||||
|
||||
### 資料庫 API
|
||||
|
||||
```
|
||||
POST http://127.0.0.1:5002/api/db/test
|
||||
- 測試資料庫連線
|
||||
|
||||
GET http://127.0.0.1:5002/api/db/tables
|
||||
- 列出所有資料表
|
||||
```
|
||||
|
||||
### LLM API
|
||||
|
||||
```
|
||||
POST http://127.0.0.1:5002/api/llm/test/gemini
|
||||
- 測試 Gemini API
|
||||
|
||||
POST http://127.0.0.1:5002/api/llm/test/deepseek
|
||||
- 測試 DeepSeek API
|
||||
|
||||
POST http://127.0.0.1:5002/api/llm/test/openai
|
||||
- 測試 OpenAI API
|
||||
|
||||
POST http://127.0.0.1:5002/api/llm/test/claude
|
||||
- 測試 Claude API
|
||||
|
||||
POST http://127.0.0.1:5002/api/llm/test/all
|
||||
- 測試所有 LLM
|
||||
|
||||
POST http://127.0.0.1:5002/api/llm/generate
|
||||
- 生成內容
|
||||
```
|
||||
|
||||
## 💡 使用範例
|
||||
|
||||
### Python 範例
|
||||
|
||||
```python
|
||||
import requests
|
||||
|
||||
# 測試資料庫連線
|
||||
response = requests.post('http://127.0.0.1:5002/api/db/test')
|
||||
print(response.json())
|
||||
|
||||
# 測試 Claude API
|
||||
response = requests.post('http://127.0.0.1:5002/api/llm/test/claude')
|
||||
print(response.json())
|
||||
|
||||
# 生成內容
|
||||
response = requests.post(
|
||||
'http://127.0.0.1:5002/api/llm/generate',
|
||||
json={
|
||||
'prompt': '介紹 HR 績效評核系統',
|
||||
'provider': 'claude',
|
||||
'options': {
|
||||
'temperature': 0.7,
|
||||
'maxTokens': 200
|
||||
}
|
||||
}
|
||||
)
|
||||
print(response.json())
|
||||
```
|
||||
|
||||
### JavaScript 範例
|
||||
|
||||
```javascript
|
||||
// 測試資料庫連線
|
||||
fetch('http://127.0.0.1:5002/api/db/test', {
|
||||
method: 'POST'
|
||||
})
|
||||
.then(res => res.json())
|
||||
.then(data => console.log(data));
|
||||
|
||||
// 生成內容
|
||||
fetch('http://127.0.0.1:5002/api/llm/generate', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
prompt: '介紹 HR 績效評核系統',
|
||||
provider: 'claude',
|
||||
options: {
|
||||
temperature: 0.7,
|
||||
maxTokens: 200
|
||||
}
|
||||
})
|
||||
})
|
||||
.then(res => res.json())
|
||||
.then(data => console.log(data));
|
||||
```
|
||||
|
||||
### cURL 範例
|
||||
|
||||
```bash
|
||||
# 測試資料庫連線
|
||||
curl -X POST http://127.0.0.1:5002/api/db/test
|
||||
|
||||
# 測試 Claude API
|
||||
curl -X POST http://127.0.0.1:5002/api/llm/test/claude
|
||||
|
||||
# 生成內容
|
||||
curl -X POST http://127.0.0.1:5002/api/llm/generate \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"prompt": "介紹 HR 績效評核系統",
|
||||
"provider": "claude",
|
||||
"options": {
|
||||
"temperature": 0.7,
|
||||
"maxTokens": 200
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
## ⚙️ 環境變數設定
|
||||
|
||||
確保 [.env](.env) 檔案包含以下設定:
|
||||
|
||||
```env
|
||||
# 資料庫設定
|
||||
DB_HOST=mysql.theaken.com
|
||||
DB_PORT=33306
|
||||
DB_NAME=db_A102
|
||||
DB_USER=A102
|
||||
DB_PASSWORD=Bb123456
|
||||
|
||||
# LLM API 金鑰
|
||||
GEMINI_API_KEY=your_gemini_api_key
|
||||
DEEPSEEK_API_KEY=your_deepseek_api_key
|
||||
OPENAI_API_KEY=your_openai_api_key
|
||||
CLAUDE_API_KEY=your_claude_api_key
|
||||
|
||||
# 應用設定
|
||||
NODE_ENV=development
|
||||
FRONTEND_URL=http://127.0.0.1:5002
|
||||
```
|
||||
|
||||
## 🔧 開發模式
|
||||
|
||||
Flask 在開發模式下會:
|
||||
- ✅ 自動重新載入程式碼變更
|
||||
- ✅ 顯示詳細錯誤訊息
|
||||
- ✅ 啟用偵錯模式
|
||||
|
||||
```python
|
||||
# app.py 最後一行
|
||||
app.run(
|
||||
host='127.0.0.1',
|
||||
port=5002,
|
||||
debug=True # 開發模式
|
||||
)
|
||||
```
|
||||
|
||||
## 📊 伺服器啟動畫面
|
||||
|
||||
```
|
||||
============================================================
|
||||
🚀 HR Performance System API Server (Flask/Python)
|
||||
============================================================
|
||||
📡 Server running on: http://127.0.0.1:5002
|
||||
🌍 Environment: development
|
||||
📅 Started at: 2025-12-03 23:59:59
|
||||
============================================================
|
||||
|
||||
📚 Available endpoints:
|
||||
GET / - API information
|
||||
GET /health - Health check
|
||||
POST /api/db/test - Test database connection
|
||||
GET /api/db/tables - List all tables
|
||||
POST /api/llm/test/* - Test LLM connections
|
||||
POST /api/llm/generate - Generate content with LLM
|
||||
GET /api-proxy-example.html - API example page
|
||||
|
||||
✨ Server is ready to accept connections!
|
||||
|
||||
✅ Database connection: OK
|
||||
|
||||
* Serving Flask app 'app'
|
||||
* Debug mode: on
|
||||
WARNING: This is a development server. Do not use it in production.
|
||||
Use a production WSGI server instead.
|
||||
* Running on http://127.0.0.1:5002
|
||||
Press CTRL+C to quit
|
||||
* Restarting with stat
|
||||
```
|
||||
|
||||
## 🎯 與 Node.js 版本的比較
|
||||
|
||||
| 功能 | Flask (Python) | Express (Node.js) |
|
||||
|------|----------------|-------------------|
|
||||
| **端口** | 5002 | 3000 |
|
||||
| **語言** | Python 3.8+ | Node.js 16+ |
|
||||
| **安裝** | `pip install -r requirements.txt` | `npm install` |
|
||||
| **啟動** | `python app.py` | `npm start` |
|
||||
| **優點** | Python 生態系統、機器學習整合 | JavaScript 全棧、效能較好 |
|
||||
|
||||
兩個版本功能完全相同,可以根據團隊技術棧選擇使用!
|
||||
|
||||
## 🐛 常見問題
|
||||
|
||||
### Q1: 執行 run_flask.bat 出現錯誤
|
||||
|
||||
**A:** 確認:
|
||||
1. Python 是否已安裝並在 PATH 中
|
||||
2. 執行 `python --version` 檢查版本
|
||||
3. 是否有權限建立虛擬環境
|
||||
|
||||
### Q2: pip install 失敗
|
||||
|
||||
**A:** 嘗試:
|
||||
```bash
|
||||
# 升級 pip
|
||||
python -m pip install --upgrade pip
|
||||
|
||||
# 使用國內鏡像(中國用戶)
|
||||
pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
|
||||
```
|
||||
|
||||
### Q3: 資料庫連線失敗
|
||||
|
||||
**A:** 檢查:
|
||||
1. MySQL 伺服器是否運行
|
||||
2. `.env` 中的資料庫連線資訊是否正確
|
||||
3. 防火牆是否阻擋 33306 端口
|
||||
|
||||
### Q4: CORS 錯誤
|
||||
|
||||
**A:** Flask-CORS 已設定,但確認:
|
||||
1. 前端是否從正確的來源發送請求
|
||||
2. `.env` 中的 `FRONTEND_URL` 設定
|
||||
|
||||
### Q5: 虛擬環境啟動失敗
|
||||
|
||||
**A:** Windows 使用者可能需要:
|
||||
```bash
|
||||
# 允許執行腳本(以管理員身份執行 PowerShell)
|
||||
Set-ExecutionPolicy RemoteSigned
|
||||
```
|
||||
|
||||
## 📁 專案結構
|
||||
|
||||
```
|
||||
hr-performance-system/
|
||||
├── app.py # Flask 主程式 ⭐
|
||||
├── requirements.txt # Python 依賴 ⭐
|
||||
├── run_flask.bat # Windows 啟動腳本 ⭐
|
||||
├── run_flask.sh # Linux/Mac 啟動腳本 ⭐
|
||||
├── server.js # Node.js 版本(可選)
|
||||
├── package.json # Node.js 依賴(可選)
|
||||
├── .env # 環境變數
|
||||
├── .gitignore
|
||||
├── venv/ # Python 虛擬環境(自動建立)
|
||||
├── public/
|
||||
│ └── api-proxy-example.html
|
||||
├── config/
|
||||
├── services/
|
||||
├── routes/
|
||||
├── utils/
|
||||
└── database/
|
||||
```
|
||||
|
||||
## 🔒 安全提醒
|
||||
|
||||
- ⚠️ **開發伺服器**:Flask 內建伺服器僅供開發使用
|
||||
- ⚠️ **生產環境**:使用 Gunicorn、uWSGI 等 WSGI 伺服器
|
||||
- ⚠️ **API 金鑰**:絕不提交 `.env` 到版本控制
|
||||
- ⚠️ **HTTPS**:生產環境必須使用 HTTPS
|
||||
|
||||
## 🚀 生產環境部署
|
||||
|
||||
### 使用 Gunicorn
|
||||
|
||||
```bash
|
||||
# 安裝 Gunicorn
|
||||
pip install gunicorn
|
||||
|
||||
# 啟動
|
||||
gunicorn -w 4 -b 127.0.0.1:5002 app:app
|
||||
```
|
||||
|
||||
### 使用 Docker
|
||||
|
||||
```dockerfile
|
||||
FROM python:3.11-slim
|
||||
WORKDIR /app
|
||||
COPY requirements.txt .
|
||||
RUN pip install -r requirements.txt
|
||||
COPY . .
|
||||
CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:5002", "app:app"]
|
||||
```
|
||||
|
||||
## 📚 相關文件
|
||||
|
||||
- [README.md](README.md) - 專案說明
|
||||
- [CORS_FIX_GUIDE.md](CORS_FIX_GUIDE.md) - CORS 問題解決
|
||||
- [database/README.md](database/README.md) - 資料庫文件
|
||||
- [package.json](package.json) - Node.js 版本(可選)
|
||||
|
||||
---
|
||||
|
||||
**最後更新**: 2025-12-03
|
||||
**Python 版本**: 3.8+
|
||||
**Flask 版本**: 3.0.0
|
||||
Reference in New Issue
Block a user