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

相关推荐
MartinYeung55 分钟前
[论文学习]大语言模型越狱的机械可解释性:基于内部归因图的分析
人工智能·学习·语言模型
SurpriseDPD6 分钟前
bpftrace‑tasks 工具代码分析
开发语言·python
曾响铃7 分钟前
跻身世界人形机器人运动会工业场景赛全国前三,ROSS Harness 以全自主模式突破工业具身智能落地瓶颈
人工智能
学习星球15 分钟前
Dify深度剖析:可视化AI应用开发平台,从源码到实战
人工智能
AI大咖18 分钟前
降重侠AI怎么样?2026实测降AIGC率+论文降重真实效果
人工智能
2401_8322981025 分钟前
AI安全治理:构建可控可信的智能时代新秩序
人工智能
本原财经30 分钟前
卖游戏、筹H股,昆仑万维临IPO磨AI含金量
人工智能·游戏
新新学长搞科研37 分钟前
【上海交通大学主办】第七届医学人工智能国际学术会议(ISAIMS 2026)
人工智能·医学
桃西西呀38 分钟前
GPT-5.6 的 ultra 模式凭什么开 4 个 Agent 并行跑?——多智能体协作,是把"一个聪明人"换成"一个团队"
人工智能·llm·agent
空堂与归41 分钟前
大模型输出总不满意?用Temperature采样控制生成质量
人工智能