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

相关推荐
一点一木7 小时前
🚀 2026 年 4 月 GitHub 十大热门项目排行榜 🔥
人工智能·github
做怪小疯子8 小时前
华为笔试0429
python·numpy
Warson_L8 小时前
Dictionary
python
淡海水8 小时前
【AI模型】常见问题与解决方案
人工智能·深度学习·机器学习
HIT_Weston8 小时前
65、【Agent】【OpenCode】用户对话提示词(费米估算)
人工智能·agent·opencode
njsgcs8 小时前
我的知识是以图片保存的,我的任务状态可能也与图片有关,我把100张知识图片丢给vlm实时分析吗
人工智能
星爷AG I8 小时前
20-4 长时工作记忆(AGI基础理论)
人工智能·agi
#卢松松#9 小时前
用秒悟(meoo)制作了一个GEO查询小工具。
人工智能·创业创新
zandy10119 小时前
Agentic BI 架构实战:当AI Agent接管数据建模、指标计算与可视化全链路
人工智能·架构
数字供应链安全产品选型9 小时前
关键领域清单+SBOM:834号令下软件供应链的“精准治理“逻辑与技术落地路径
人工智能·安全