0

I'm using cherrypy to build a web service. I came across the BackgroundTaskQueue plugin and I want to use it to handle specific time-consuming operations on a separate thread.

The documentation states the usage should be like the following:

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

But, IMHO, using the bgtask object like this isn't very elegant. I would like handlers from other python modules to use this object too.

Is there a way to subscribe this plugin once, and then "share" the bgtask object among other handlers (like, for example saving it it in the cherrypy.request)?

How is this done? Does this require writing a cherrypy tool?

Remi Guan
  • 21,506
  • 17
  • 64
  • 87

1 Answers1

0

Place

queue = BackgroundTaskQueue(cherrypy.engine)

in a separate file named, for instance, tasks.py. This way you create module tasks. Now you can 'import tasks' in other modules and queue is a single instance

For example, in a file called test.py:

import tasks
def test(): print('works!')
tasks.queue.put(log, test)
Daniel Nuriyev
  • 635
  • 6
  • 10