Redis向SSE事件处理程序提供了错误的结果。
以下代码适用于Python CLI
def stream():
pubsub = reds.pubsub()
pubsub.subscribe('chat')
for message in pubsub.listen():
return 'data: %s\n\n' % message['data']
返回例如'data: hello\n\n'
当我从Redis终端PUBLISH chat "hello"
时。
但是Bottle.py中的以下内容不是
@get('/stream')
def stream():
response.content_type = 'text/event-stream'
response.set_header('Cache-Control', 'no-cache')
pubsub = reds.pubsub()
pubsub.subscribe('chat')
for message in pubsub.listen():
return 'data: %s\n\n' % message['data']
@get('/test')
def test():
return """
<!DOCTYPE html>
<html>
<body>
<h1>Getting server updates</h1>
<div id="result"></div>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource('/stream');
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
</body>
</html>
"""
当我访问127.0.0.1:8000/test
时,我会每隔几秒钟看到以下内容
1
1
1
1
1
1
1
1
...
我应该看到的地方
hello
hi
howdy
...
如果我改变
@get('/stream')
def stream():
response.content_type = 'text/event-stream'
response.set_header('Cache-Control', 'no-cache')
pubsub = reds.pubsub()
pubsub.subscribe('chat')
for message in pubsub.listen():
return 'data: %s\n\n' % message['data']
要
@get('/stream')
def stream():
response.content_type = 'text/event-stream'
response.set_header('Cache-Control', 'no-cache')
now = datetime.datetime.now().time().replace(microsecond=0)
return "data: %s\n\n"%now
它有效,但这不是我需要的,它是一个以毫秒为单位返回当前时间的函数。
鉴于它在Python CLI中没有问题,那么这里可能出现什么问题?我正在试图解决一些容易做的问题。
答案 0 :(得分:0)
咄!解决方案很简单。
我不得不改变
def stream():
pubsub = reds.pubsub()
pubsub.subscribe('chat')
for message in pubsub.listen():
return 'data: %s\n\n' % message['data']
到
def stream():
pubsub = reds.pubsub()
pubsub.subscribe('chat')
for message in pubsub.listen():
yield 'data: %s\n\n' % message['data']
基本上将return
更改为yield
。但奇怪的是,产量首先没有起作用..