同步 I/O 不是不能用,但边界要清楚
如果整个路由都是同步逻辑,直接写同步路由通常更简单:
import requests
from fastapi import APIRouter
router = APIRouter()
@router.get("/health-from-legacy")
def health_from_legacy():
response = requests.get("https://legacy.example.com/health")
return response.json()
FastAPI 会把这个同步路由放在线程池里跑。对纯同步场景,这往往比“硬写 async”更诚实。
这里有一个容易混淆的点: 同步路由不适合直接去调用异步 service 拿结果。
# 这样写拿到的是 coroutine 对象,不是实际结果
@router.get("/users/{user_id}")
def get_user(user_id: int):
result = get_user_from_async_db(user_id) # 返回 <coroutine object>
return result # 不是你想要的数据
如果你的 service 本身依赖异步数据库或异步 HTTP,路由通常也应该一起变成 async def。