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)}")
相关推荐
johnny2331 天前
Django生态:Django-admin、Django-Compressor、Django-grappelli、django-rules
django
weixin_BYSJ19872 天前
django在线图书销售平台---附源码16192
java·javascript·spring boot·python·django·flask·php
kobe_OKOK_2 天前
django外键字段会自动在数据库字段后面加上_id
数据库·django·sqlite
梅雅达编程笔记3 天前
零基础学 Python 第14章 | 模块、包与第三方库
开发语言·python·django·numpy·pandas
梅雅达编程笔记3 天前
零基础学 Python 第15章 | 类与对象:面向对象编程入门
开发语言·python·django·numpy·pandas
不能只会打代码3 天前
Day 006 — Multi-Agent + MCP/A2A + 安全 + 可观测性
agent·token·sse·multi-agent·mcp·a2a
2401_868534784 天前
OSPF经典案例分析
python·django
前端炒粉4 天前
Vue2 SSE 流式对话完整前端代码
前端·sse·流式输出
不瘦80斤不改名4 天前
全家桶、乐高积木与类型引擎:重新认识 Django、Flask 与 FastAPI
django·flask·fastapi
sugar__salt6 天前
从零理解 LLM 流式输出:Vue3 + DeepSeek API 实战
前端·人工智能·状态模式·sse·流式输出