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

相关推荐
袁俪10 小时前
智能体搭建
人工智能
Json____10 小时前
基于 FastAPI + Vue3 的高校选课管理系统技术解析
后端·fastapi·wwwoop.com
SunnyDays101110 小时前
如何使用 Python 添加和编辑 Excel VBA 宏(无需安装 Excel)
开发语言·python·excel·vba
创新技术阁10 小时前
FastapiAdmin 定时任务实现原理与新建任务实操指南
前端·后端·fastapi
2601_9622959910 小时前
Python+Appium 自动化测试:从基础语法到 PO 模式设计,构建稳定测试框架
自动化测试·python·appium·测试框架·po模式
开源量化GO10 小时前
先确认策略想法能不能变成规则
人工智能·python
拜托多多指教10 小时前
【Pytest框架学习】分层架构
python·pytest
luckystar513~10 小时前
Hermes 实战 :调度——cron 6:00 无人值守跑日报
人工智能·agent·智能体·hermes·实战专栏
3A Cloud10 小时前
Huashu Design:把 AI Agent 变成一间以 HTML 为画布的设计工作室
前端·人工智能·html
xwz小王子10 小时前
Science Robotics | 从模仿到创造:BeyondMimic如何让机器人“学到”人类的敏捷与多才多艺
人工智能·机器人