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)}")
相关推荐
意疏1 天前
程序员兼职如何选择靠谱的软件外包平台 与 我的避坑经验
django
vx_biyesheji00011 天前
豆瓣电影推荐系统 | Python Django 协同过滤 Echarts可视化 深度学习 大数据 毕业设计源码
大数据·爬虫·python·深度学习·django·毕业设计·echarts
玄同7651 天前
Python 后端三剑客:FastAPI/Flask/Django 对比与 LLM 开发选型指南
人工智能·python·机器学习·自然语言处理·django·flask·fastapi
B站_计算机毕业设计之家1 天前
豆瓣电影推荐系统 | Python Django Echarts构建个性化影视推荐平台 大数据 毕业设计源码 (建议收藏)✅
大数据·python·机器学习·django·毕业设计·echarts·推荐算法
一路向北⁢1 天前
Spring Boot 3 整合 SSE (Server-Sent Events) 企业级最佳实践(三)
java·spring boot·后端·sse
luoluoal2 天前
基于深度学习的web端多格式纠错系统(源码+文档)
python·mysql·django·毕业设计·源码
wxin_VXbishe2 天前
springboot旅游信息管理系统-计算机毕业设计源码21675
java·c++·spring boot·python·spring·django·php
云和数据.ChenGuang2 天前
python 面向对象基础入门
开发语言·前端·python·django·flask
墨染青竹梦悠然3 天前
基于Django+React的个人财务管理系统
python·django·毕业设计
墨染青竹梦悠然3 天前
基于Django+vue的图书借阅管理系统
前端·vue.js·后端·python·django·毕业设计·毕设