当前位置: 首页 > 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.dtcms.com/a/293911.html

相关文章:

  • 基于数据挖掘的短视频点赞影响因素分析【LightGBM、XGBoost、随机森林、smote】
  • 探索大语言模型(LLM):提升 RAG 性能的全方位优化策略
  • 深圳TCL外包岗位要去吗?
  • NLP基础全面解析:从概念到实践
  • 主要分布在背侧海马体(dHPC)CA1区域(dCA1)的时间细胞对NLP中的深层语义分析的积极影响和启示
  • WebGIS 中常用空间数据格式
  • Linux网络:网络层-IP协议
  • 金仓 KEMCC 非云环境初始化与纳管指南
  • 每日一算:华为-批萨分配问题
  • 异常的传递性|模块的概念和导入|自定义模块并导入
  • Nginx + PM2 实现Express API + React 前端 本地测试服务器搭建
  • 从 Shell 脚本到 Go 应用:使用 Kiro AI 助手完成 Harpoon 项目重构的完整实践
  • [特殊字符] 从数据库无法访问到成功修复崩溃表:一次 MySQL 故障排查实录
  • 闲庭信步使用图像验证平台加速FPGA的开发:第三十二课——车牌识别的FPGA实现(4)车牌字符的分割定位
  • 基于Tornado的WebSocket实时聊天系统:从零到一构建与解析
  • 简单理解现代Web应用架构:从简单到企业级
  • 棱镜技术在光谱相机中应用
  • 【Unity实战100例】Unity资源下载系统开发流程详解(移动端、PC端 ,局域网控制台服务)
  • K8s:离线部署Kubernetes1.26.12及采用外部Harbor
  • DApp的未来发展趋势是什么?
  • solidity从入门到精通 第四章:智能合约的生命周期
  • 糖尿病数据分析:血压与年龄关系可视化
  • 二重循环之练习输入行数,打印等腰三角形
  • 同一个端口无法同时配置基于 server_name 的 HTTP(非加密)和 HTTPS(加密)
  • 【矩阵专题】Leetcode73.矩阵置零
  • 西门子 S7-1500分布式 I/O通信 :PROFINET IO 与 PROFIBUS DP详解(下)
  • 9、STM32的启动过程
  • Ubuntu系统下FFmpeg源码编译安装
  • 面试150 建立四叉树
  • 电脑32位系统能改64位系统吗