跳转至

FastAPI 部署

性能依赖

安装 uvloophttptools 以获得更好的性能(Uvicorn 检测到会自动启用):

pip install uvloop httptools

uvloop 不支持 Windows。可用环境标记处理:uvloop; sys_platform != 'win32'

生产启动

uvicorn src.main:app --host 0.0.0.0 --port 8000 --workers 4

或使用 gunicorn + uvicorn worker:

gunicorn src.main:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000

API 文档控制

非公开 API 在生产环境隐藏文档:

from pydantic_settings import BaseSettings

class Config(BaseSettings):
    ENVIRONMENT: str = "production"

settings = Config()

SHOW_DOCS_ENVIRONMENTS = ("local", "staging")

app_configs = {"title": "My API"}
if settings.ENVIRONMENT not in SHOW_DOCS_ENVIRONMENTS:
    app_configs["openapi_url"] = None

app = FastAPI(**app_configs)

线程池调整

默认线程池只有 40 个线程。高并发场景可在 lifespan 里调大:

import anyio
from contextlib import asynccontextmanager

@asynccontextmanager
async def lifespan(app: FastAPI):
    limiter = anyio.to_thread.current_default_thread_limiter()
    limiter.total_tokens = 100
    yield

app = FastAPI(lifespan=lifespan)

中间件性能

避免使用 BaseHTTPMiddleware@app.middleware("http") 也是它的包装),有性能损耗。 需要中间件时优先实现纯 ASGI 中间件:

class MyMiddleware:
    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        if scope["type"] == "http":
            # 前置处理
            pass
        await self.app(scope, receive, send)