使用FastAPI做人工智能后端服务器时,接口内的操作不是异步操作的解决方案

在做AI模型推理的接口时,这时候接口是非异步的,但是uvicorn运行FastAPI时就会出现阻塞所有请求。

这时候需要解决这个问题:

api.py

python 复制代码
import asyncio
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import time
import io
import uvicorn

app = FastAPI()


def my_io(num):
    print(num)
    time.sleep(20)

@app.get("/hello")
async def hello():
    loop = asyncio.get_event_loop()

    # my_io 里包含不支持异步操作的代码, 所以就使用线程池来配合实现了。
    future = loop.run_in_executor(None , my_io , 666)
    response = await future
    print("运行完成", response)
    return {"message" : "success"}

def read_image_data(image_path : str):
     with open(image_path , "rb") as fr:
            datas = fr.read()
            return datas

@app.get("/show_image/{image_path:path}")
async def show_image(image_path : str):
    datas = await asyncio.get_event_loop().run_in_executor(None , read_image_data , image_path)
    bytes = io.BytesIO(datas)
    return StreamingResponse(bytes , media_type="image/png")
    

if __name__ == "__main__":
    uvicorn.run("api:app", host="0.0.0.0", port=10001, reload=True)

完美解决!!!perfect!!!

相关推荐
人工智能AI技术36 分钟前
Gemma 4 C# 部署教程:手机/边缘设备离线运行
人工智能
青瓷程序设计1 小时前
基于YOLO的火灾烟雾检测系统~Python+目标检测+算法模型+2026原创
python·yolo·目标检测
立莹Sir2 小时前
Spring Bean 生命周期详解
java·python·spring
JHC0000008 小时前
基于Ollama,Milvus构建的建议知识检索系统
人工智能·python·milvus
mOok ONSC8 小时前
SpringBoot项目中读取resource目录下的文件(六种方法)
spring boot·python·pycharm
ZPC82108 小时前
如何创建一个单例类 (Singleton)
开发语言·前端·人工智能
AppOS8 小时前
手把手教你 Openclaw 在 Mac 上本地化部署,保姆级教程!接入飞书打造私人 AI 助手
人工智能·macos·飞书
workflower8 小时前
AI制造-推荐初始步骤
java·开发语言·人工智能·软件工程·制造·需求分析·软件需求
wukangjupingbb8 小时前
解析Computational driven drug discovery: from structure to clinic
人工智能·机器学习
tctasia8 小时前
TCT Asia 2026现场观察:中国增材制造,已经进入“规模化时刻”(上)
大数据·人工智能·制造