Vas*_*nth 5 python cherrypy python-webbrowser server-sent-events angularjs
我正在开发一个简单的网络应用程序,它是用 Angular 和 Cherrypy 完成的(目前正在制作原型)。我正在上传两个文件,然后使用子进程(popen)调用cherrypy中的外部python程序来处理它们。到目前为止我能够做到这一点。我想要实现的是将外部程序的输出(我通过 popen 捕获)传递给客户端。我的问题是,我正在尝试在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()
Run Code Online (Sandbox Code Playgroud)
这是 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...");
};
Run Code Online (Sandbox Code Playgroud)
我已经在这个博客中看过这个问题。然而,在从服务器端调用该函数时,EventSource 对象上的 onmessage 事件不会触发。我的理解是,您可以从服务器端调用该函数,它会捕获来自浏览器的事件。是我错了还是设置错了?
所以我发现,对于 SSE,我需要以特定格式发送数据。IE
或者对于 json
data: "{\n
data: "msg" : "foo", \n
data: "id" : "boo", \n
data: "}\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'}
Run Code Online (Sandbox Code Playgroud)
,现在发送的消息带有
'重试:n 微秒'
这将每 n 微秒发送一次数据。现在,EventSource onmessage 事件正在被触发,我很高兴地读取从服务器发送的程序的输出。:)
SSE 的好读物(正如许多帖子中提到的):这里
| 归档时间: |
|
| 查看次数: |
2019 次 |
| 最近记录: |