FastAPI 部署
性能依赖
安装 uvloop 和 httptools 以获得更好的性能(Uvicorn 检测到会自动启用):
uvloop 不支持 Windows。可用环境标记处理:
uvloop; sys_platform != 'win32'
生产启动
或使用 gunicorn + uvicorn worker:
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 中间件: