← 返回 Skills 市场
FastAPI Flask Proxy
作者
hunwenpinghao
· GitHub ↗
· v1.0.0
· MIT-0
115
总下载
0
收藏
0
当前安装
1
版本数
在 OpenClaw 中安装
/install fastapi-flask-proxy
功能描述
FastAPI + Flask 混合部署最佳实践。解决路由定义、API 代理等常见问题。适用于需要同时运行 FastAPI API 和 Flask 前端的场景。
使用说明 (SKILL.md)
FastAPI + Flask 混合部署指南
当你需要同时运行 FastAPI 后端 API 和 Flask 前端服务时,需要注意以下关键问题。
架构模式
┌─────────────────────────────────────────┐
│ 用户浏览器 │
└─────────────────┬───────────────────────┘
│ :15000
▼
┌─────────────────────────────────────────┐
│ Flask (端口 15000) │
│ - 静态页面 │
│ - API 代理 → FastAPI │
└─────────────────┬───────────────────────┘
│ 内部调用
▼
┌─────────────────────────────────────────┐
│ FastAPI (端口 18000) │
│ - REST API │
│ - 业务逻辑 │
└─────────────────────────────────────────┘
核心踩坑与解决方案
1. FastAPI 路由定义位置 ⚠️
问题: 路由定义在 if __name__ == "__main__": 之后,导致路由未被注册。
错误示例:
from fastapi import FastAPI
app = FastAPI()
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=18000)
# ❌ 路由定义在 main 之后,不会被加载!
@app.get("/api/hello")
def hello():
return {"message": "Hello"}
正确示例:
from fastapi import FastAPI
app = FastAPI()
# ✅ 路由定义在 main 之前
@app.get("/api/hello")
def hello():
return {"message": "Hello"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=18000)
2. Flask API 代理 ⚠️
问题: 前端通过 Flask (15000端口) 访问,但 API 在 FastAPI (18000端口),存在跨域问题。
解决方案: 在 Flask 中添加 API 代理。
from flask import Flask, request, Response
import requests
app = Flask(__name__)
FASTAPI_BASE = "http://localhost:18000"
# 代理 GET 请求
@app.route("/api/\x3Cpath:path>", methods=["GET"])
def proxy_get(path):
resp = requests.get(f"{FASTAPI_BASE}/api/{path}", params=request.args)
return Response(resp.content, status=resp.status_code,
headers={"Content-Type": "application/json"})
# 代理 POST 请求
@app.route("/api/\x3Cpath:path>", methods=["POST"])
def proxy_post(path):
resp = requests.post(f"{FASTAPI_BASE}/api/{path}",
json=request.get_json())
return Response(resp.content, status=resp.status_code,
headers={"Content-Type": "application/json"})
# 代理 DELETE 请求
@app.route("/api/\x3Cpath:path>", methods=["DELETE"])
def proxy_delete(path):
resp = requests.delete(f"{FASTAPI_BASE}/api/{path}")
return Response(resp.content, status=resp.status_code,
headers={"Content-Type": "application/json"})
# 代理 PUT 请求
@app.route("/api/\x3Cpath:path>", methods=["PUT"])
def proxy_put(path):
resp = requests.put(f"{FASTAPI_BASE}/api/{path}",
json=request.get_json())
return Response(resp.content, status=resp.status_code,
headers={"Content-Type": "application/json"})
3. 导入问题 ⚠️
问题: 新增的模型类在路由文件中未导入,导致 NameError。
解决方案: 确保所有使用的类都已导入。
# models.py
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from database import Base
class Trajectory(Base):
__tablename__ = "trajectories"
id = Column(Integer, primary_key=True)
# ...
class Annotation(Base):
__tablename__ = "annotations"
id = Column(Integer, primary_key=True)
trajectory_id = Column(Integer, ForeignKey("trajectories.id"))
# ...
# main.py (FastAPI)
from models import Trajectory, Annotation, Response, Prompt # ✅ 全部导入
@app.delete("/api/trajectories/{trajectory_id}")
def delete_trajectory(trajectory_id: int, db: Session = Depends(get_db)):
# 现在可以正确访问所有模型
annotation = db.query(Annotation).filter(
Annotation.trajectory_id == trajectory_id
).first()
# ...
4. 删除操作的级联处理
问题: 删除主记录时,关联的外键记录如何处理?
方案 A: 数据库级联删除(推荐)
class Trajectory(Base):
__tablename__ = "trajectories"
id = Column(Integer, primary_key=True)
annotations = relationship("Annotation", cascade="all, delete-orphan")
方案 B: 手动删除关联记录
@app.delete("/api/trajectories/{trajectory_id}")
def delete_trajectory(trajectory_id: int, db: Session = Depends(get_db)):
# 先删除关联的 annotations
db.query(Annotation).filter(
Annotation.trajectory_id == trajectory_id
).delete()
# 再删除主记录
trajectory = db.query(Trajectory).filter(
Trajectory.id == trajectory_id
).first()
if trajectory:
db.delete(trajectory)
db.commit()
return {"status": "deleted"}
完整启动脚本
#!/bin/bash
# 启动 FastAPI 后端 (后台运行)
cd /app
python -m uvicorn api:app --host 0.0.0.0 --port 18000 &
FASTAPI_PID=$!
# 启动 Flask 前端
python frontend.py
# 清理
kill $FASTAPI_PID 2>/dev/null
Docker Compose 配置
version: '3.8'
services:
api:
build: .
command: python -m uvicorn api:app --host 0.0.0.0 --port 18000
ports:
- "18000:18000"
web:
build: .
command: python frontend.py
ports:
- "15000:15000"
depends_on:
- api
environment:
- FASTAPI_URL=http://api:18000
最佳实践总结
- 路由定义: 始终在
if __name__ == "__main__":之前定义所有路由 - API 代理: 前端服务需要代理 API 请求到后端
- 导入管理: 新增模型类后,确保在所有使用的地方导入
- 级联删除: 设计好外键关系的级联策略
- 错误处理: 代理请求时正确传递错误状态码
相关项目
- Preference Alignment System:
[email protected]:/data/algorithm/user/wphu/OmniMLLM/preference-align
安全使用建议
This is primarily a how-to guide (no code files or installers). Before using: ensure your Python environment has the packages used in the examples (uvicorn, requests, SQLAlchemy) or adapt the examples to your dependency management; review and test the proxy code carefully (it strips headers and may remove cookies or auth headers unintentionally); verify the docker-compose network and FASTAPI_URL env usage in your deployment; and check the 'Related project' reference (wphu@gpu506...) — it points to an external/internal resource and may be irrelevant or unintended. If you need to run this in production, consider a more robust proxy (preserve headers, forward status codes and auth), add explicit dependency installation, and run inside an isolated environment or container.
功能分析
Type: OpenClaw Skill
Name: fastapi-flask-proxy
Version: 1.0.0
The skill bundle is a documentation and code snippet guide for deploying a hybrid FastAPI and Flask architecture. It provides standard examples for API proxying, routing, and database management using SQLAlchemy. While it includes a reference to an internal project path ([email protected]), there is no evidence of malicious intent, data exfiltration, or prompt injection designed to compromise the agent or the host system.
能力评估
Purpose & Capability
Name/description match the instructions: the SKILL.md explains mixing FastAPI and Flask, routing issues, proxy patterns, startup scripts and docker-compose. Small incoherence: the examples rely on Python packages (uvicorn, requests, SQLAlchemy) but the skill only declares python3 as a required binary and does not declare these dependencies.
Instruction Scope
Instructions stay within the stated scope (routing, proxying, startup, deletion/cascade patterns). They show concrete code for a Flask->FastAPI proxy, process startup/cleanup, and Docker Compose. Note: the proxy examples drop most headers (only sets Content-Type) which affects cookies/auth and error propagation; the doc also references an external/internal project path ([email protected]:...) that is outside the skill's immediate scope and should be reviewed before use.
Install Mechanism
No install spec (instruction-only) — lowest install risk. Nothing is downloaded or written to disk by the skill itself.
Credentials
The skill declares no required environment variables or credentials, which is proportionate. However the examples expect certain runtime packages and environment values (e.g., FASTAPI_URL in the docker-compose example) that are not declared. Also the referenced related-project path suggests ties to an internal resource — this is not a credential request but is unexpected.
Persistence & Privilege
The skill does not request persistent presence (always: false) and does not attempt to modify other skills or system-wide settings.
如何使用
- 确保已安装 OpenClaw(本地或 Docker 部署)
- 在对话框中输入安装命令:
/install fastapi-flask-proxy - 安装完成后,直接呼叫该 Skill 的名称或使用
/fastapi-flask-proxy触发 - 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v1.0.0
Initial release: FastAPI + Flask hybrid deployment best practices
元数据
常见问题
FastAPI Flask Proxy 是什么?
FastAPI + Flask 混合部署最佳实践。解决路由定义、API 代理等常见问题。适用于需要同时运行 FastAPI API 和 Flask 前端的场景。 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 115 次。
如何安装 FastAPI Flask Proxy?
在 OpenClaw 或 Claude Code 对话框中运行命令「/install fastapi-flask-proxy」即可一键安装,无需额外配置。
FastAPI Flask Proxy 是免费的吗?
是的,FastAPI Flask Proxy 完全免费,采用 MIT-0 许可证,可自由下载、安装和使用。
FastAPI Flask Proxy 支持哪些平台?
FastAPI Flask Proxy 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。
谁开发了 FastAPI Flask Proxy?
由 hunwenpinghao(@hunwenpinghao)开发并维护,当前版本 v1.0.0。
推荐 Skills