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

相关推荐
潘正翔5 分钟前
DeepSeek Harness从0到1部署
人工智能·开发·codex·deepseek·harness·deepseekharness·cludecode
青禾8376 分钟前
Linux 系统信息、权限管理与 Python 并发编程(协程与线程)完全指南
linux·python
bulingg11 分钟前
bert输入长度有限,如何处理超长文本?
人工智能·深度学习·bert
曲无忆13 分钟前
密码学三大核心技术解析
python·密码学
神奇小汤圆14 分钟前
DeepSeek Harness 这波,搞得全世界都在安装 Node.js
人工智能
qq210846295314 分钟前
在python中什么是 self 和 cls?
开发语言·前端·python
nanawinona22 分钟前
2026年手工思路量化后,工具重点会怎样变化
人工智能·python
武子康26 分钟前
DeepSeek Harness、Codex、Claude Code、LangGraph 应该怎么选:先判断你缺的是产品、底盘还是工作流
人工智能·llm·agent
美团技术团队28 分钟前
美团搜索3.0:LLM 语义表征在排序模型的探索与应用
人工智能