Skip to content
返回部署

部署 FastAPI 应用

异步 Python API 框架,自动 OpenAPI 文档,通过 Uvicorn/Gunicorn 部署到容器或 serverless。

平台进阶

为什么

FastAPI 利用 async/await 和 Pydantic 请求验证,在 Python 中达到 Node.js 级性能。自动生成 OpenAPI 文档和类型安全减少样板和 bug。

何时使用

需要异步 I/O、自动文档和验证的现代 Python API 用 FastAPI。新项目优于 Flask;遗留 WSGI 中间件选 Flask。

如何做

1. ASGI 服务器 — uvicorn app:app --host 0.0.0.0 --port 8000 2. 生产 — gunicorn app:app -w 4 -k uvicorn.workers.UvicornWorker 3. Docker — python:3.12-slim,uvicorn CMD 4. Serverless — mangum 适配 Lambda,或 Vercel Python 5. 自动文档 — /docs(Swagger)和 /redoc(ReDoc)自动生成 6. 异步 — I/O 密集用 async def,sync def 卸载到线程池 7. CORS — CORSMiddleware 跨源前端

示例

# main.py from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float @app.get("/health") async def health(): return {"ok": True} @app.post("/items") async def create(item: Item): return {"created": item} # Dockerfile FROM python:3.12-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . EXPOSE 8000 CMD ["gunicorn", "main:app", "-w", "4", "-k", "uvicorn.workers.UvicornWorker", "-b", "0.0.0.0:8000"] # Vercel — api/index.py from mangum import Mangum from main import app handler = Mangum(app)

常见问题

  • ⚠异步路由中阻塞调用 — async def 中同步 I/O 阻塞事件循环,用 run_in_executor 或 sync def
  • ⚠Uvicorn worker 未利用 CPU — 单 worker = 单核,用 Gunicorn 配 UvicornWorker
  • ⚠Pydantic v1 vs v2 不匹配 — FastAPI 版本固定 Pydantic,混用导致运行时错误

最佳实践

  • ✓I/O 密集处理用 async def(DB、HTTP),CPU 密集用 sync def — FastAPI 将 sync 卸载到线程池
  • ✓始终为请求/响应定义 Pydantic 模型 — 免费获得验证、文档和类型安全
  • ✓设置健康检查和优雅关闭 — 处理 SIGTERM 以在退出前排空进行中的请求

常见问题解答