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)}")
相关推荐
weixin_4316004411 小时前
前端对接 SSE 的两种常见方式
前端·后端·学习·ai·sse·nest.js
2401_868534782 天前
综合脚本实战!自动备份、清日志、服务器巡检
python·django
weixin_BYSJ19872 天前
springboot酒店管理系统--附源码27436
java·spring boot·python·随机森林·贪心算法·eclipse·django
vx-程序开发2 天前
django医院预约挂号系统---附源码23353
java·javascript·spring boot·python·eclipse·django·php
weixin_BYSJ19872 天前
springboot医疗信息管理系统---附源码17465
java·javascript·spring boot·python·django·flask·php
vx-程序开发3 天前
springboot农产品运输服务平台---附源码75498
java·javascript·spring boot·python·eclipse·django·php
John jj3 天前
拆解 Telegram 群组频道收录市场:三类方案,一个可运行的评分模型,目前TG中文人工评分加模型评分机制——LetsTG收录“快速”、“无门槛”
大数据·后端·python·深度学习·搜索引擎·django·全文检索
2401_868534783 天前
论信息系统安全保障规划与设计
python·django
Python私教3 天前
如意 Django CRM 容器化实战:后端、前端、数据库、Redis 的协同启动逻辑
前端·数据库·django
我欲扶摇九万里3 天前
SpringAI前置基础学习记录(一)|SSE协议及具体实现(SseEmitter)
java·人工智能·sse