← Back to Skills Marketplace
hunwenpinghao

FastAPI Flask Proxy

by hunwenpinghao · GitHub ↗ · v1.0.0 · MIT-0
cross-platform ✓ Security Clean
115
Downloads
0
Stars
0
Active Installs
1
Versions
Install in OpenClaw
/install fastapi-flask-proxy
Description
FastAPI + Flask 混合部署最佳实践。解决路由定义、API 代理等常见问题。适用于需要同时运行 FastAPI API 和 Flask 前端的场景。
README (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

最佳实践总结

  1. 路由定义: 始终在 if __name__ == "__main__": 之前定义所有路由
  2. API 代理: 前端服务需要代理 API 请求到后端
  3. 导入管理: 新增模型类后,确保在所有使用的地方导入
  4. 级联删除: 设计好外键关系的级联策略
  5. 错误处理: 代理请求时正确传递错误状态码

相关项目

  • Preference Alignment System: [email protected]:/data/algorithm/user/wphu/OmniMLLM/preference-align
Usage Guidance
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.
Capability Analysis
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.
Capability Assessment
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.
How to Use
  1. Make sure OpenClaw is installed (local or Docker)
  2. Run the install command in chat: /install fastapi-flask-proxy
  3. After installation, invoke the skill by name or use /fastapi-flask-proxy
  4. Provide required inputs per the skill's parameter spec and get structured output
Version History
v1.0.0
Initial release: FastAPI + Flask hybrid deployment best practices
Metadata
Slug fastapi-flask-proxy
Version 1.0.0
License MIT-0
All-time Installs 0
Active Installs 0
Total Versions 1
Frequently Asked Questions

What is FastAPI Flask Proxy?

FastAPI + Flask 混合部署最佳实践。解决路由定义、API 代理等常见问题。适用于需要同时运行 FastAPI API 和 Flask 前端的场景。 It is an AI Agent Skill for Claude Code / OpenClaw, with 115 downloads so far.

How do I install FastAPI Flask Proxy?

Run "/install fastapi-flask-proxy" in the OpenClaw or Claude Code chat to install it in one step — no extra setup required.

Is FastAPI Flask Proxy free?

Yes, FastAPI Flask Proxy is completely free, licensed under MIT-0. You can download, install and use it at no cost.

Which platforms does FastAPI Flask Proxy support?

FastAPI Flask Proxy is cross-platform and runs anywhere OpenClaw / Claude Code is available (cross-platform).

Who created FastAPI Flask Proxy?

It is built and maintained by hunwenpinghao (@hunwenpinghao); the current version is v1.0.0.

💬 Comments