Django实现SSE流

文章目录

一、代码示例

python 复制代码
def llm_stream_generator(agent_url: str, headers: dict, request_data: dict):
    # 调用大模型SSE接口
    response = requests.post(
        url=agent_url,
        headers=headers,
        json=request_data,
        stream=True,
        timeout=10
    )
    response.raise_for_status()

    # 流式读取响应数据
    for line in response.iter_lines():
        if line:
            # 解析大模型返回的SSE数据(根据实际返回格式调整)
            line_data = line.decode('utf-8').strip()
            if line_data.startswith('data:'):
                yield line_data + "\n\n"
python 复制代码
from django.http import StreamingHttpResponse
from django.views.decorators.http import require_GET
from rest_framework.exceptions import APIException

from .utils import llm_stream_generator

# 存储所有连接的客户端
clients = []

@require_GET
def sse_endpoint(request):
    try:
        llm_gen = llm_stream_generator(agent_url="http://127.0.0.1:27080/v1/chat-messages",
                                       headers={"authorization": "Bearer app-xxxxxxxxx"})
        # 3. 返回流式响应
        stream_response = StreamingHttpResponse(
            llm_gen,
            content_type="text/event-stream; charset=utf-8",
        )
        return stream_response
    except Exception as e:
        raise APIException(f"服务器内部错误: {str(e)}")
相关推荐
luoluoal9 小时前
基于python的机器学习的文本分类系统(源码+文档)
python·mysql·django·毕业设计·源码
电商API&Tina1 天前
【电商API接口】关于电商数据采集相关行业
java·python·oracle·django·sqlite·json·php
高斯的手稿08011 天前
Django里面,多个APP的url设置,每个APP单独对应HTML设置
数据库·django·html
计算机毕设指导61 天前
基于微信小程序+django连锁火锅智慧餐饮管理系统【源码文末联系】
java·后端·python·mysql·微信小程序·小程序·django
高斯的手稿08011 天前
Django里面,多个APP的url怎么设置
django
秋氘渔1 天前
Django DRF + SimpleJWT 实战 (一):基于纯自定义 Model 的 Token 鉴权与踩坑指南
django·前后端分离·simplejwt·drf·token鉴权
二等饼干~za8986682 天前
碰一碰发视频系统源码开发搭建--技术分享
java·运维·服务器·重构·django·php·音视频
高洁012 天前
基于Tensorflow库的RNN模型预测实战
人工智能·python·算法·机器学习·django
luoluoal3 天前
基于python的RSA算法的数字签名生成软件(源码+文档)
python·mysql·django·毕业设计