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

python3写一个异步流式 http 接口服务调用大模型(async, stream, sanic)---6.2

python3写一个异步流式 http 接口服务调用大模型(async, stream, sanic)

python3写一个异步流式 http 接口服务调用大模型(async, stream, sanic)

python3写一个异步流式 http 接口服务调用大模型(async, stream, sanic),异步适合处理I/O密集型操作(文件/网络请求),特别地,调用大模型等待时间特别长。记录一下!

一、Sanic介绍

Sanic是一个Python3的web服务器和web框架,旨在快速运行。它允许使用Python 3.5中添加的async/await语法。

安装

pip install sanic

二、异步接口代码实现

# !/usr/bin/python
# -*- coding: utf-8 -*-
# @time    : 2025/07/19 18:34
# @author  : Mo
# @function: async http
import json
import traceback
import time
import sys
import ospath_sys = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.append(path_sys)
print(path_sys)from sanic.views import HTTPMethodView
from sanic.log import logger
from sanic import response
from sanic import Sanic
import asyncioapp = Sanic("add_async")
app.config.RESPONSE_TIMEOUT = 96   # 超时时间配置
rsp_kwargs = {"content_type": "text/event-stream","headers": {"Cache-Control": "no-cache","Connection": "keep-alive","X-Accel-Buffering": "no"}}async def n_range_stream(n=None, **kwargs):"""  异步程序xxx   """await asyncio.sleep(1)n = n or 10for i in range(n):await asyncio.sleep(0.01)yield json.dumps({"index": i}, ensure_ascii=False) + "\n"class textStreamView(HTTPMethodView):def __init__(self) -> None:super().__init__()async def post(self, request):"""   简单流式输出  """if "application/json" in request.content_type:data = request.jsonelse:data = request.formasync def stream_generator(response):# 调用异步流式响应函数async for content in n_range_stream(**data):# 将每个响应块发送给客户端# await asyncio.sleep(0.01)await response.write(content)# 返回流式响应return response.ResponseStream(stream_generator, **rsp_kwargs)app.add_route(textStreamView.as_view(),uri="/text_stream",methods=["POST", "GET"],version=1,name="add")# ### 测试异步, async
# import time
# time_start = time.time()
# resp = asyncio.run(n_range_stream(a=2, b=3))
# print(resp)
# time_end = time.time()
# print(time_end - time_start)if __name__ == '__main__':app.run(host="0.0.0.0",port=8032,workers=1,access_log=True)

接口访问

接口: http://127.0.0.1:8032/v1/text_stream
入参:

{"n": 10}

在这里插入图片描述

参考

  • sanic

希望对你有所帮助!

[外链图片转存中…(img-ZcI2LCY1-1753262174740)]

参考

  • sanic

希望对你有所帮助!

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

相关文章:

  • 若依前后端分离版学习笔记(二)——系统菜单介绍
  • 前端资源缓存优化案例:深入探讨 Nginx 配置中的 Cache-Control 头部叠加问题
  • 【科研绘图系列】R语言绘制黑白填充等显著性标记条形图
  • Java按模板导出Excel
  • Redis能完全保证数据不丢失吗?
  • 《WebGL与Three.js打造会“讲故事“的虚拟博物馆》
  • 氢气传感器在氢燃料电池中的应用与技术保障
  • 《狼道》:生存智慧与处世哲学
  • python 字符串常用处理函数
  • 判断矩形能否放入多边形内——cad c# 二次开发实现
  • docker的镜像与推送
  • 卡尔曼滤波数据融合
  • GaussDB null的用法
  • mac测试ollama llamaindex
  • c++--面向对象封装--实践
  • 【2025/07/23】GitHub 今日热门项目
  • git的使用,推送仓库github
  • 【数据结构】——时间与空间复杂度深度解析
  • 第一章:Go语言基础入门之Hello World与Go程序结构
  • 设置低秩适配器(LoRA)
  • 苍穹外卖DAY11
  • 【网安-小迪】Day5:反弹SHELL不回显带外正反向连接防火墙出入站文件下载
  • android studio打包vue
  • vue写的app设置角标
  • 智能小e-集成配置
  • vue3与ue5通信-工具类
  • 2025年电赛--电源题赛前押题
  • 【每日算法】专题十八_BFS 解决拓扑排序
  • 刷完jetpack后无法打开安装的浏览器的解决办法useful
  • SSM框架中关于Spring MVC的技术问题