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

相关推荐
luojiezong几秒前
锐捷极简以太彩光网络解决方案入选《“AI中国”生态范式案例集(2025)》
网络·人工智能
周杰伦_Jay几秒前
【LangGraph】图结构智能体框架核心特性
python·开源
Light603 分钟前
再见,REST API?你好,MCP Server!AI时代后端开发新范式
java·人工智能·rest api·ai agent·spring ai·mcp
鲨莎分不晴4 分钟前
强化学习第四课 —— 深度强化学习:Policy Gradient 入门
人工智能·学习·机器学习
zhaodiandiandian5 分钟前
理性抉择方可行远——企业AI转型的路径选择与风险管控
人工智能
serve the people6 分钟前
tensorflow 零基础吃透:tf.function 与 RaggedTensor 的结合使用
人工智能·tensorflow·neo4j
中年程序员一枚17 分钟前
让postman调用python的开发接口,链接sqlite数据库,让前后联动起来
数据库·python·postman
火火PM打怪中19 分钟前
空窗期的自我探索
人工智能·职场和发展
测试人社区-千羽20 分钟前
AI重塑API测试数据生成的时代背景
人工智能·测试工具·程序人生·自动化·测试覆盖率
爱写Bug的小孙27 分钟前
Tools、MCP 和 Function Calling
开发语言·人工智能·python·ai·ai编程·工具调用