在请求处理程序之间共享CherryPy的BackgroundTaskQueue对象

时间:2015-10-23 08:21:10

标签: python cherrypy object-sharing

我使用cherrypy构建Web服务。我遇到了BackgroundTaskQueue插件,我想用它来处理单独线程上特定的耗时操作。

文档说明用法应如下所示:

import cherrypy
from complicated_logging import log

bgtask = BackgroundTaskQueue(cherrypy.engine)
bgtask.subscribe()

class Root(object):

    def index(self):
        bgtask.put(log, "index was called", ip=cherrypy.request.remote.ip))
        return "Hello, world!"
    index.exposed = True

但是,恕我直言,使用像这样的bgtask对象并不是很优雅。我希望其他python模块的处理程序也能使用这个对象。

有没有办法订阅此插件一次,然后"分享"其他处理程序中的bgtask对象(例如,将其保存在cherrypy.request中)?

这是怎么做到的?这是否需要编写一个樱桃工具?

1 个答案:

答案 0 :(得分:0)

放置

queue = BackgroundTaskQueue(cherrypy.engine)

在一个名为的单独文件中,例如 tasks.py 。这样您就可以创建模块任务。 现在您可以在其他模块中“导入任务”,队列是单个实例

例如,在名为 test.py 的文件中:

import tasks
def test(): print('works!')
tasks.queue.put(log, test)
相关问题