Python服务器发送的事件返回格式是什么?
我有一个django项目,使用服务器发送的事件和redis pubsub系统。 代码如下: 我使用JavaScript代码打开事件Python服务器发送的事件返回格式是什么?,python,django,real-time,Python,Django,Real Time,我有一个django项目,使用服务器发送的事件和redis pubsub系统。 代码如下: 我使用JavaScript代码打开事件 var eventSource=new eventSource(“/tweets/stream”); eventSource.addEventListener('message',函数(e){ console.log(消息) },假); 然后在我的python代码中,我使用redis subscribe处理它。当我获得新数据并响应请求时。没有数据显示。所以我认为我
var eventSource=new eventSource(“/tweets/stream”);
eventSource.addEventListener('message',函数(e){
console.log(消息)
},假);
然后在我的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")
从django.http导入HttpResponse,StreamingHttpResponse
...
...
返回StreamingHttpResponse(stream_data(),content_type=“text/event stream”)
使用StreamingHttpResponse而不是HttpResponse将修复此问题
from django.http import HttpResponse, StreamingHttpResponse
...
...
return StreamingHttpResponse(stream_data(), content_type="text/event-stream")