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}
相关推荐
Shi_haoliu4 小时前
python安装操作流程-FastAPI + PostgreSQL简单流程
python·postgresql·fastapi
ZH15455891314 小时前
Flutter for OpenHarmony Python学习助手实战:API接口开发的实现
python·学习·flutter
小宋10214 小时前
Java 项目结构 vs Python 项目结构:如何快速搭一个可跑项目
java·开发语言·python
一晌小贪欢4 小时前
Python 爬虫进阶:如何利用反射机制破解常见反爬策略
开发语言·爬虫·python·python爬虫·数据爬虫·爬虫python
躺平大鹅5 小时前
5个实用Python小脚本,新手也能轻松实现(附完整代码)
python
yukai080085 小时前
【最后203篇系列】039 JWT使用
python
独好紫罗兰5 小时前
对python的再认识-基于数据结构进行-a006-元组-拓展
开发语言·数据结构·python
Dfreedom.5 小时前
图像直方图完全解析:从原理到实战应用
图像处理·python·opencv·直方图·直方图均衡化
铉铉这波能秀5 小时前
LeetCode Hot100数据结构背景知识之集合(Set)Python2026新版
数据结构·python·算法·leetcode·哈希算法