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

相关推荐
有为少年23 分钟前
从独立性、相关性到复杂动力系统
人工智能·深度学习·机器学习·数学建模
阿里云大数据AI技术24 分钟前
【新模型速递】PAI-Model Gallery云上一键部署Qwen3.5模型
人工智能
KG_LLM图谱增强大模型27 分钟前
AgentRxiv:迈向协作式自主科学研究新范式
人工智能·知识图谱
人工智能培训30 分钟前
超级人工智能(AGI)是否是大模型的必然发展方向?
人工智能·深度学习·逻辑回归·agi·具身智能·大模型应用工程师·企业ai培训
小白菜又菜35 分钟前
Leetcode 235. Lowest Common Ancestor of a Binary Search Tree
python·算法·leetcode
Omigeq37 分钟前
1.2.2 - 采样搜索算法(以RRT和RRT*为例) - Python运动规划库教程(Python Motion Planning)
开发语言·人工智能·python·机器人
凌云拓界39 分钟前
TypeWell全攻略(二):热力图渲染引擎,让键盘发光
前端·后端·python·计算机外设·交互·pyqt·数据可视化
mantch41 分钟前
教程:Nano-Banana Pro,谷歌官方指南
人工智能·aigc
小白菜又菜1 小时前
Leetcode 234. Palindrome Linked List
python·算法·leetcode