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

相关推荐
纪伊路上盛名在6 分钟前
机器学习中的固定随机种子方案
人工智能·机器学习·数据分析·随机种子
SteveSenna12 分钟前
项目:Trossen Arm MuJoCo
人工智能·学习·算法
兢谨网安13 分钟前
AI安全:从技术加固到体系化防御的实战演进
人工智能·安全·网络安全·渗透测试
CoderJia程序员甲24 分钟前
GitHub 热榜项目 - 日榜(2026-03-29)
人工智能·ai·大模型·github·ai教程
龙腾AI白云32 分钟前
什么是AI智能体(AI Agent)
人工智能·深度学习·自然语言处理·数据分析
Sagittarius_A*36 分钟前
监督学习(Supervised Learning)
人工智能·学习·机器学习·监督学习
向上的车轮43 分钟前
AI智能体开发:需求分析要点与实战指南
人工智能·需求分析
fobwebs1 小时前
wordpress GEO插件指南
人工智能·wordpress·geo·ai搜索优化·geo优化
GMATG_LIU1 小时前
电子背散射衍射(EBSD)技术的优势
人工智能
今天也要学习吖1 小时前
开源AI智能客服系统AI-CS
人工智能·ui·chatgpt·golang·开源·gemini·智能客服系统