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)}")
相关推荐
码界奇点6 小时前
基于Django的超市管理系统设计与实现
数据库·python·django·sqlite·毕业设计·源代码管理
B站_计算机毕业设计之家7 小时前
AI大模型:Deepseek美食推荐系统 机器学习 协同过滤推荐算法+可视化 Django框架 大数据毕业设计(源码)✅
python·算法·机器学习·数据分析·django·推荐算法·美食
yq1982043011568 小时前
构建高可用资源导航平台:基于Django+Scrapy的分布式架构实践
分布式·scrapy·django
森爱。9 小时前
web开发全家桶(django+前端+数据库)
前端·python·django
一路向北⁢1 天前
Spring Boot 3 整合 SSE (Server-Sent Events) 企业级最佳实践(一)
java·spring boot·后端·sse·通信
luoluoal1 天前
基于opencv的疲劳检测系统(源码+文档)
python·mysql·django·毕业设计·源码
一路向北⁢1 天前
Spring Boot 3 整合 SSE (Server-Sent Events) 企业级最佳实践(二)
java·数据库·spring boot·sse·通信
ktoking1 天前
Stock Agent AI 模型的选股器实现 [七]
人工智能·python·django
BYSJMG2 天前
2026计算机毕设推荐:基于大数据的车辆二氧化碳排放量可视化分析系统
大数据·vue.js·python·mysql·django·课程设计
WangYaolove13143 天前
基于opencv的疲劳检测系(源码+文档)
python·mysql·django·毕业设计·源码