我正在开发一个简单的网络应用程序,该应用程序是使用 angular 和 cherrypy 完成的(目前正在制作原型(prototype))。我正在上传两个文件,然后使用 subprocess (popen) 在 cherrypy 中调用外部 python 程序来处理它们。到目前为止,我能够做到这一点。我想要实现的是将外部程序的输出(我通过 popen 捕获)传递给客户端。我的问题是,我正在尝试在 cherrypy 上设置服务器发送的事件但没有成功。
这是我公开的 cherrypy 方法(来自网络的示例):
@cherrypy.expose
def getUpdate(self):
#Set the expected headers...
cherrypy.response.headers["Content-Type"] = "text/event-stream;charset=utf-8"
def content():
yield "Hello,"
yield "world"
return content()
这是 javascript 客户端代码(我启用了 CORS 并且可以正常工作):
var sseEvent = new EventSource('http://localhost:8090/getUpdate');
sseEvent.onmessage = function (event) {
console.log(event);
};
sseEvent.onopen = function (event) {
//console.log("I have started...");
};
我看过这个question在这个blog .然而,在从服务器端调用该函数时,EventSource 对象上的 onmessage 事件并未触发。我的理解是,您可以从服务器端调用该函数,它会从浏览器捕获事件。是我错了还是设置有误?
最佳答案
所以我发现对于 SSE,我需要以特定格式发送数据。即
- 数据:“富\n\n”
或者对于 json
数据:“{\n 数据:“消息”:“富”,\n 数据:“id”:“boo”,\n 数据:“}\n\n
我想要的是重试格式,在 n 秒后继续轮询服务器。所以现在的 cherrypy 函数是:
@cherrypy.expose
def getUpdate(self, _=None):
cherrypy.response.headers["Content-Type"] = "text/event-stream;charset=utf-8"
if _:
data = 'retry: 200\ndata: ' + str( self.prog_output) + '\n\n'
return data
else:
def content():
data = 'retry: 200\ndata: ' + str( self.prog_output) + '\n\n'
return data
return content()
getUpdate._cp_config = {'response.stream': True, 'tools.encode.encoding':'utf-8'}
,现在发送的消息带有
'retry: n microseconds'
这将每 n 微秒发送一次数据。现在 EventSource onmessage 事件被触发,我很高兴地读取从服务器发送的程序的输出。 :)
SSE 的好读物(如许多帖子中所述):here
关于python - 如何设置 cherrypy 服务器发送的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35927900/