【问题标题】:What is Python Server-sent event return Format?Python 服务器发送的事件返回格式是什么?
【发布时间】:2016-02-04 22:29:42
【问题描述】:

我有一个使用服务器发送事件和 redis pubsub 系统的 django 项目。 代码如下:

我使用 JavaScript 代码打开事件

var eventSource = new EventSource("/tweets/stream");

eventSource.addEventListener('message', function(e) {
    console.log(message) 
}, false);

然后在我的 python 代码中,我使用 redis subscribe 来处理它。当我得到新数据并响应请求时。没有数据显示。所以我认为我的回复格式有问题。

def stream(request):
   def stream_data():
      REDIS_CONF = {
          'host': 'localhost',
          'port': 6379,
          'db': 1,
     }
     red = redis.StrictRedis(**REDIS_CONF)
     pubsub = red.pubsub()
     pubsub.subscribe('@NBA')
     for message in pubsub.listen():
        long_string = '''
        id: 123 \n\n
        data: 123123123 \n
        '''
        return long_string

    return HttpResponse(stream_data(), content_type="text/event-stream")

【问题讨论】:

    标签: python django real-time


    【解决方案1】:
    从 django.http 导入 HttpResponse, StreamingHttpResponse ... ... 返回 StreamingHttpResponse(stream_data(), content_type="text/event-stream")

    使用 StreamingHttpResponse 而不是 HttpResponse 将解决此问题。

    【讨论】:

      猜你喜欢
      • 2013-01-11
      • 2023-04-03
      • 2013-12-01
      • 1970-01-01
      • 2018-11-25
      • 1970-01-01
      • 1970-01-01
      • 2020-06-20
      • 1970-01-01
      相关资源
      最近更新 更多