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)}")
相关推荐
呱呱复呱呱9 天前
Django CBV 源码解读:一个请求是怎么找到你的 get() 方法的
python·django
码云骑士15 天前
31-慢查询排查全流程(上)-Django-Debug-Toolbar与EXPLAIN入门
后端·python·django
龙腾AI白云15 天前
数字孪生和世界模型,二者的技术边界正在慢慢融合吗?
人工智能·django·知识图谱
码云骑士15 天前
30-在线图书管理系统-Django从零搭建到上线部署完整实战
后端·python·django
2601_9618752416 天前
花生十三资源盘|电子版|全科
python·django·flask·virtualenv·scikit-learn·pygame·tornado
码云骑士16 天前
28-Docker部署Django(下)-docker-compose编排与静态文件处理
docker·容器·django
码云骑士16 天前
23-Django-ORM的N+1问题-select_related与prefetch_related详解
后端·python·django
摸摸芋16 天前
Django框架(1)
后端·python·django
码云骑士16 天前
27-Docker部署Django(上)-从2GB到180MB的镜像瘦身实战
docker·容器·django
杰杰79816 天前
DRF的分页讲解-入门篇 三个基础分页类介绍
python·django