使用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!!!

相关推荐
workflower6 分钟前
以光量子为例,详解量子获取方式
数据仓库·人工智能·软件工程·需求分析·量子计算·软件需求
壹氿10 分钟前
Supersonic 新一代AI数据分析平台
人工智能·数据挖掘·数据分析
张较瘦_16 分钟前
[论文阅读] 人工智能 | 搜索增强LLMs的用户偏好与性能分析
论文阅读·人工智能
我不是小upper28 分钟前
SVM超详细原理总结
人工智能·机器学习·支持向量机
Yxh1813778455434 分钟前
抖去推--短视频矩阵系统源码开发
人工智能·python·矩阵
Humbunklung1 小时前
PySide6 GUI 学习笔记——常用类及控件使用方法(多行文本控件QTextEdit)
笔记·python·学习·pyqt
取酒鱼食--【余九】1 小时前
rl_sar实现sim2real的整体思路
人工智能·笔记·算法·rl_sar
Jamence1 小时前
多模态大语言模型arxiv论文略读(111)
论文阅读·人工智能·语言模型·自然语言处理·论文笔记
火车叼位1 小时前
使用 uv 工具在 Windows 系统快速下载安装与切换 Python
python