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

相关推荐
豪气的程序猿26 分钟前
电商图片工作流怎么选?Lingko AI 对比折叠键盘主图与详情页
人工智能
80s77730 分钟前
动态代理和静态代理的区别,动态代理怎么提高网络安全性
python
小刘快学习1 小时前
把 AI 账单拆到部门:企业 AI 网关的精准分账思路
人工智能
米小虾1 小时前
你让监控模型读的思维链,可能是攻击者写好的剧本
人工智能
deepseek231 小时前
Iris 开源搜索智能体拆解:35B 与 397B 中文仅差 0.3 分,上下文管理胜过堆参数
人工智能·ai agent·开源模型
ai小陈1 小时前
CUDA Stream实战:让数据传输与GPU计算真正重叠
人工智能·深度学习·ai·pdf·云计算·gpu算力
residual_fan1 小时前
【学术论文】航空发动机故障诊断智能体:基于持续对比强化学习的动态优化方法
人工智能·算法·数据挖掘·数据分析
东风破_1 小时前
从 RAG 到 Agentic RAG:第二步,把复杂问题拆开再检索
人工智能
dehuisun1 小时前
第07篇:RAG+Agent 部署架构、资源评估与私有化方案
人工智能
米小虾2 小时前
拆给 8 个子智能体,只拿回 2.3 倍信息:多智能体分解的产出守恒律
人工智能·agent