当前位置: 首页 > news >正文

使用FastAPI做人工智能后端服务器时,接口内的操作不是异步操作的解决方案

在做AI模型推理的接口时,这时候接口是非异步的,但是uvicorn运行FastAPI时就会出现阻塞所有请求。

这时候需要解决这个问题:

api.py:

import asyncio
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import time
import io
import uvicornapp = 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 futureprint("运行完成", 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!!! 

http://www.lryc.cn/news/455156.html

相关文章:

  • Leetcode 3312. Sorted GCD Pair Queries
  • 用 Delphi 做了一个简单的 CMS
  • ASK, PSK, FSK, DPSK
  • 【Linux】认识Linux内核中进程级别的文件结构体【files_struct】&文件IO模型初步演示
  • [Offsec Lab] ICMP Monitorr-RCE+hping3权限提升
  • Studying-多线程学习Part4 - 异步并发——async future、packaged_task、promise
  • 【Java基础】用Scanner类获取控制台输入
  • 微服务seata解析部署使用全流程
  • Linux性能调优技巧
  • python 实现sha1算法
  • ejb-ref元素
  • Perl 子程序(函数)
  • ElasticSearch 备考 -- Snapshot Restore
  • 【Linux】进程替换、命令行参数及环境变量(超详解)
  • MySQL事务日志—redo日志介绍
  • 告别音乐小白!字节跳动AI音乐创作工具,让你一键变作曲家!
  • 空心正方形图案
  • 【EXCEL数据处理】000020 案例 保姆级教程,附多个操作案例。EXCEL使用表格。
  • 虾皮Shopee大数据面试题及参考答案
  • 重学SpringBoot3-集成Redis(六)之消息队列
  • LeetCode 134 Gas Station 解题思路和python代码
  • 服务攻防
  • leetcode 力扣算法题 快慢指针 双指针 19.删除链表的倒数第n个结点
  • 网络五层模型:物理层、数据链路层、网络层、传输层、应用层,分别解决了什么问题?
  • OpenCV视频I/O(18)视频写入类VideoWriter之初始化 VideoWriter 对象的函数open()的使用
  • 大数据处理从零开始————4.认识HDFS分布式文件系统
  • jwt认证课件讲解
  • 【判断推理】逻辑基础
  • AcWing 655:天数转换 ← 整除、求余
  • 【解决办法】git clone报错unable to access ‘xxx‘: SSL certificate problem: