HTML 原文 · 完整 Markdown · 纯文本 · 分段目录 · ← 上一段 · 下一段 →

02-FastAPI 里什么时候该用 async,什么时候该用线程池

第 6 / 13 段:最容易犯的错:`async def` 里混入阻塞调用

FastAPI 工程化实践 · 发布 2026-03-28 · 更新 2026-11-11 · 标签:FastAPI、Async、Performance

最容易犯的错:async def 里混入阻塞调用

下面这种写法在代码上看起来没问题,在并发下会很糟:

import requests
from fastapi import APIRouter

router = APIRouter()

@router.get("/orders/{order_id}")
async def get_order(order_id: int):
    response = requests.get(f"https://example.com/orders/{order_id}")
    return response.json()

问题不是 requests 不好,而是它是同步阻塞调用。你把它放进 async def,事件循环就拿不到控制权,其他协程也没法顺利切换。

很多人第一次踩坑时,都会把问题归咎于“FastAPI 不够快”或者“Python 异步不稳定”。 但更常见的真实原因其实是:async def 里混入了阻塞同步 I/O。