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

相关推荐
刘天远1 分钟前
Agent成本核算实现:事件表、状态分布与Python归集
前端·数据库·人工智能·python
Ai小禾2 分钟前
智谱清言对话数据怎么导入到另外一个智谱清言账号里去?AI导出鸭的工程化解法
人工智能
Dawson Zhu5 分钟前
《Agentic Design Patterns》第 11 章导读:目标设定与监控(Goal Setting and Monitoring)
人工智能·语言模型·架构·aigc·agi
技灵AI9 分钟前
AI 带货视频会被限流吗?AIGC 标识、功效演示、同质化量产与画质四项判定对照
人工智能·aigc·音视频·ai电商·seedance
容小智11 分钟前
金融投研引入工作智能体(Agent):如何穿透概念核算真实商业价值?
大数据·人工智能·ai·金融·agent
Python图像识别13 分钟前
40-【2027毕设】YOLO11面部口罩检测识别系统 - Python完整源码+PyQt5界面+训练模型+数据集
python·qt·课程设计
赵大仁17 分钟前
开源清单怎么维护才不烂掉?GitHub Actions 每周查死链 + 软 404 检测实录
python·ci/cd·自动化·开源项目·踩坑·github actions·json schema
玩AI的奶茶19 分钟前
24GB 显存能跑多大的模型?参数量、精度与显存占用对照表
人工智能·python·算法·ai·aigc·gpu算力·算力租赁
kimnoic20 分钟前
Python操作Git命令的详细指南
开发语言·python
larance22 分钟前
[菜鸟教程] 机器学习教程十一课-数据理解
人工智能·机器学习