【发布时间】:2016-03-17 13:56:38
【问题描述】:
我正在尝试设置一个带有 Cherrypy 后端的网络应用程序。 Web 应用程序只是一个程序的 GUI,它将在服务器中运行并解析一些文件。我希望能够做的是当它上传文件,并在后端执行程序时,将进程的输出报告回浏览器。
我已经用我的 Cherrypy 服务器设置了 CORS 和服务器发送事件。我不确定这是服务器发送事件还是 WebSockets 的情况。我真的在寻找一种方法来有效地实现此功能(返回报告)并能够为多个客户端提供服务(cherrypy 已经支持)。
我尝试过的:
- 设置 SSE 事件,该事件发送一个变量(公共)保存子流程的输出。这适用于单个客户。由于对象属性在cherrypy中是持久的。 (在此question 中介绍)。
- 然后我尝试进行会话。这是我卡住的地方,会话元素集在 SSE 函数中消失了。我尝试了很多东西,但都没有成功。 即使是这样,我也不确定如何避免在与 SSE 的请求之间共享数据。
SSE方法:
@cherrypy.expose
def getUpdate(self, _=None):
print "Horay! %s" % cherrypy.session.get('pid') # <-- this is None, even though its set in the main method
try:
cherrypy.session['youknow'] = "iknow"
cherrypy.session.save()
except Exception as e:
raise e
if _:
data = 'data: meh meh...\n\n'
return data
else:
def content(data=None):
if self.dataReady and self.prog_output is not None:
response = ""
for output in self.prog_output:
response += 'data: %s \n\n' % str(output)
data = 'retry: 2000\n%s \n\n' % response
return data
elif self.dataFinished:
self.dataFinished = False
return 'data: + Done\n\n'
return content()
getUpdate._cp_config = {'response.stream': True, 'tools.encode.encoding': 'utf-8'}
主要方法:
@cherrypy.expose
@cherrypy.tools.noBodyProcess()
def uploadFile(self, file=None):
theFile = file
# Save the pid in the user's session (a thread-safe place)
cherrypy.session['pid'] = "pid"
cherrypy.session.save()
// calls the external program and parses here in a different thread, which updates the prog_output variable
Cherrypy 配置:
if __name__ == '__main__':
cherrypy.tools.CORS = cherrypy._cptools.HandlerTool(CORS)
cherrypy.config.update({
"tools.CORS.on": True,
"server.socket_port": 8090,
"server.thread_pool": 8,
"tools.sessions.on": True,
# 'tools.sessions.storage_type': "File",
# 'tools.sessions.storage_path': 'sessions',
# 'tools.sessions.locking': 'explicit',
这只是解决会话问题的一个案例,还是我应该在这个特定用例中使用 WebSockets。
【问题讨论】:
标签: python websocket cherrypy server-sent-events