【问题标题】:How to run an external program and report back the browser asyn in Cherrypy如何运行外部程序并在 Cherrypy 中异步报告浏览器
【发布时间】: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


    【解决方案1】:

    我能够通过将问题分成两部分来解决这个问题(不久前)。

    • 首先,我上传了需要处理的文件。然后服务器返回这些文件路径和新文件的名称作为响应。
    • 从服务器(文件路径、新文件名)获得响应后,我会调用服务器上的 SSE 事件函数(即 www.server.com/runProc/filepath/filepath2/newfilepath),该函数运行进程并流式传输输出回浏览器。

    我的问题是我试图一口气做到这一点,这反过来又造成了不必要的问题。此外,这样就不需要会话或跨多个请求保存数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-10
      • 1970-01-01
      • 2015-11-21
      • 1970-01-01
      • 2011-10-26
      • 2011-09-23
      相关资源
      最近更新 更多