已将 Custom React Agent API 从 FastAPI 迁移到 Flask,保持了相同的功能和接口,但使用了不同的 Web 框架。
# 旧版本 (FastAPI)
pip install fastapi uvicorn aiohttp
# 新版本 (Flask)
pip install flask aiohttp
特性 | FastAPI | Flask |
---|---|---|
自动API文档 | ✅ 自动生成 /docs |
❌ 无自动文档 |
请求验证 | ✅ Pydantic 自动验证 | ⚠️ 手动验证 |
异步支持 | ✅ 原生支持 | ⚠️ 需要 asyncio.run() |
类型提示 | ✅ 完整支持 | ⚠️ 基础支持 |
性能 | 🚀 更高 | 📊 中等 |
学习曲线 | 📈 中等 | 📊 简单 |
# FastAPI
@app.post("/api/chat", response_model=ChatResponse)
async def chat_endpoint(request: ChatRequest):
...
# Flask
@app.route("/api/chat", methods=["POST"])
def chat_endpoint():
data = request.get_json()
...
# FastAPI
return ChatResponse(code=200, message="成功", data=result)
# Flask
return jsonify({"code": 200, "message": "成功", "data": result})
# FastAPI
raise HTTPException(status_code=400, detail="错误信息")
# Flask
return jsonify({"error": "错误信息"}), 400
# 方式1:直接运行
python api.py
# 方式2:使用 flask 命令
export FLASK_APP=api.py
flask run --host=0.0.0.0 --port=8000
# 健康检查
curl http://localhost:8000/health
# 功能测试
python test_api.py
# Flask 中调用异步 Agent 方法
agent_result = asyncio.run(_agent_instance.chat(...))
# 手动验证替代 Pydantic
def validate_request_data(data):
errors = []
if not data.get('question'):
errors.append('问题不能为空')
# ... 更多验证
if errors:
raise ValueError('; '.join(errors))
# 暂时不启用跨域支持
# 如果需要跨域支持,可以安装 flask-cors
# pip install flask-cors
pip install gunicorn
gunicorn -w 4 -b 0.0.0.0:8000 api:app
pip install uwsgi
uwsgi --http :8000 --wsgi-file api.py --callable app --workers 4
异步函数调用错误
asyncio.run()
包装异步调用CORS 错误
pip install flask-cors
端口占用
# 查看端口占用
netstat -an | grep 8000
迁移完成: Flask 版本已完全实现所有 FastAPI 功能,接口保持 100% 兼容。