Python FastAPI异步路由_Python FastAPI怎么定义异步端点处理IO任务

FastAPI异步路由需用async def定义端点,配合httpx、asyncpg等异步库;避免同步操作,CPU密集任务用run_in_executor;依赖注入也支持async def,可统一管理资源生命周期。

异步路由的核心是用 async def 定义端点

FastAPI 原生支持异步,只要把路由函数声明为 async def,它就会在异步事件循环中运行。这特别适合等待数据库查询、HTTP 请求、文件读写等 I/O 密集型操作,避免阻塞主线程。

直接 await 支持异步的库(如 httpx、asyncpg、aiomysql)

不要在异步端点里调用同步库(比如 requests、psycopg2),否则会阻塞事件循环。应改用对应的异步版本:

  • HTTP 调用:用 httpx.AsyncClient 替代 requests
  • PostgreSQL:用 asyncpgSQLModel 配合 async engine
  • MySQL:用 aiomysqlasyncmy
  • Redis:用 redis-pyfrom redis.asyncio import Redis

避免在 async 路由里执行 CPU 密集或同步阻塞操作

如果必须调用同步函数(比如处理图像、解析大 JSON、加密计算),要用 loop.run_in_executor 把它扔进线程池,防止拖慢整个应用:

  • from concurrent.futures import ThreadPoolExecutor
  • 在依赖或端点中通过 await loop.run_in_executor(executor, sync_func, *args) 调用
  • 不推荐用 asyncio.to_thread()(Python 3.9+),FastAPI 运行环境通常兼容,但需确认 event loop 可用

依赖注入也支持异步,可统一管理资源生命周期

async def 写依赖函数,FastAPI 会自动 await。例如数据库连接、认证校验、配置加载等都可以异步化:

  • 定义 async def get_db(): ... yield db,配合 @contextlib.asynccontextmanager
  • 在路由参数中声明 db: AsyncSession = Depends(get_db)
  • 异常处理、日志记录、中间件同样可异步编写