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之认证与权限
python·django
言之。3 小时前
Django原子请求
数据库·django·sqlite
@zulnger5 小时前
Django 框架
数据库·django·sqlite
开开心心_Every6 小时前
一键隐藏窗口到系统托盘:支持任意软件摸鱼
服务器·前端·python·学习·edge·django·powerpoint
❆VE❆20 小时前
WebSocket与SSE深度对比:技术差异、场景选型及一些疑惑
前端·javascript·网络·websocket·网络协议·sse
Java水解1 天前
JWT鉴权的实现:从原理到 Django + Vue3
django
WangYaolove13141 天前
基于深度学习的身份证识别考勤系统(源码+文档)
python·mysql·django·毕业设计·源码
河码匠1 天前
Django rest framework 搜索、排序和分页
django
WangYaolove13142 天前
Python基于大数据的电影市场预测分析(源码+文档)
python·django·毕业设计·源码
luoluoal2 天前
基于python大数据的电影市场预测分析(源码+文档)
python·mysql·django·毕业设计·源码