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

相关推荐
二川bro7 分钟前
零门槛上手DeepSeek Harness,从零自制arxiv搜索插件
人工智能
cxr82820 分钟前
数学的本质:关系、模式与不变量的结构世界
人工智能·算法·机器学习
东莞和裕包装21 分钟前
如何管控广州定制纸箱生产中的啤切精度与印刷色差质量问题
大数据·运维·网络·人工智能
AIDANHANG22 分钟前
放开靠时间戳对日志前先核请求ID跨服务传播与采样关联
前端·人工智能
牛肉胡辣汤32 分钟前
手握实战经验,分享AI工程落地的踩坑与收获
人工智能
2601_9632827733 分钟前
山地复杂环境对讲机通信失效实战排查与组网优化方案
人工智能·语音识别
两万五千个小时34 分钟前
DeepSeek Harness 从 0 开始:15 schedule 域(定时任务)
人工智能·程序员·架构
IT智慧客073135 分钟前
2026年3月前端面试:20个高频考点全解析
人工智能
火山引擎开发者社区39 分钟前
Agent Plan × DeepSeek Harness 实践指南
人工智能
桃西西呀39 分钟前
DeepSeek Harness vs Codex CLI vs Claude Code,谁该用什么
人工智能