FastAPI异步方法中调用同步方法

前言

在异步方法中调用同步方法,会直接阻塞整个事件循环,导致应用在执行同步方法期间无法处理其他任何并发请求,从而拖垮整个服务的性能。

为了解决这个问题,核心思路是将同步方法交给外部线程池去执行。

方法1, 使用 to_thread

Python 3.9 后可以使用 asyncio.to_thread 方法,将同步函数跑在独立的线程中,并返回一个协程供 await

python 复制代码
import asyncio
import time
from fastapi import FastAPI

app = FastAPI()

def sync_task(name: str):
    time.sleep(2) 
    return f"Hello {name}, sync task done!"

@app.get("/async-call")
async def async_endpoint():
    result = await asyncio.to_thread(sync_task, "World")
    
    return {"message": result}

方法2, 直接定义同步路由

FastAPI支持定义同步路由,FastAPI会自动在一个外部线程池中运行该函数。不过出于代码整体设计的考虑,个人不建议这么做。

方法3, 使用 run_in_threadpool

FastAPI 基于 Starlette, 而 Starlette 提供一个工具函数 run_in_threadpool,这种方式类似于 asyncio.to_thread,在某些老版本的 FastAPI 或特定的 contextvars 传递场景下更常用。

python 复制代码
from fastapi.concurrency import run_in_threadpool

@app.get("/method3")
async def starlette_endpoint():
    result = await run_in_threadpool(sync_task, "Starlette")
    return {"message": result}

方法4, 使用进程池

对于CPU密集型任务,应该使用多进程ProcessPoolExecutor来操作

python 复制代码
import concurrent.futures
import math
from fastapi import FastAPI

app = FastAPI()
# 创建一个全局进程池
executor = concurrent.futures.ProcessPoolExecutor()

def cpu_intensive_calculation(n: int):
    # 模拟重度 CPU 计算
    return sum(math.isqrt(i) for i in range(n))

@app.get("/cpu-bound-task")
async def cpu_task():
    loop = asyncio.get_running_loop()
    result = await loop.run_in_executor(executor, cpu_intensive_calculation, 10**7)
    return {"result": result}
相关推荐
东莞市云毅网络有限公司8 小时前
用 Node 做收录快照的周对比:差集、阈值与告警
python·sqlite·自动化运维·geo·数据监测
山楂树の9 小时前
Python Pandas 数据处理:数据读取、筛选、清洗、排序与分组
开发语言·python·pandas
Logintern099 小时前
langgraph 图编译的聊天机器人
python·langgraph
xurileidian10 小时前
第 22 篇 · 边玩边学Python · 双等号与 is 不是一回事
开发语言·python·spring
钱栈up12 小时前
GitHub热榜实测|Sherlock:一个用户名搜遍全网
python·开源·github
geovindu12 小时前
python: Gradient Boosting
开发语言·后端·python·算法·boosting
Agent世界12 小时前
发布台账字段漂移:1265 条记录里 190 条没有标题
python·自动化运维
用户2986985301414 小时前
Python 自动化处理 Word:按规则查找并高亮关键文本
python·api·编程语言
人工智能技术咨询.15 小时前
什么才算高质量数据集
python
DanCheng-studio15 小时前
毕业设计项目 机器视觉指纹识别特征对比算法(源码+论文)
python·毕业设计·毕设