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

相关推荐
随风@飘扬3 分钟前
CCS Theia中F28035 工程调试连接排障记录
人工智能
code2cat4 分钟前
【随笔】MCP工具注解的信任边界:四个提示如何参与调用决策
python·ai agent·mcp
用户7275107796315 分钟前
程序员第一次控制工业步进电机:Python + Modbus RTU,从串口报文到自动定位(附可运行代码)
人工智能
AI袋鼠帝6 分钟前
WorkBuddy悄悄干了件大事,下一代Office真来了!
人工智能·agent
慢云智慧空间7 分钟前
从设备智能到空间理解,慢云科技如何重新定义智慧建筑
python·科技
浮链序7 分钟前
用 Claude Haiku 5.5 做子智能体路由,把 Agent 成本砍掉六成
人工智能·python·llm
IT_陈寒8 分钟前
为什么你应该学习JavaScript?
前端·人工智能·后端
谁在黄金彼岸10 分钟前
Qwen-Image-2512-vs-2.1-实测对比
人工智能
ProbeX11 分钟前
Ollama到底是什么?能跑多大模型?
人工智能
梧桐AI13 分钟前
手写ReAct Agent:从mock循环到公网部署的完整记录
人工智能