Passing the web request context transparently to the celery task

I have a multi-user setting where I would like to pass certain information about a specific client, in particular request.host for the celery task, where ideally it should be available in a global variable. Is there any way to set this transparent to the application?

the task will be called the same:

my_background_func.delay(foo, bar)

the task is defined in the same way, except that it has access to a global variable called "request" with the attribute "host":

@celery_app.task
def my_background_func(foo, bar):
    print "running the task for host:" + request.host

thanks

EDIT

that's how I decided it ...

class MyTask(Task):
    abstract = True
    def delay(self, *args, **kwargs):
        return self.apply_async(args, kwargs, headers={'host': request.host})

on the client:

 @celery_app.task(base=MyTask, bind=True)
 def hellohost(task):
     return "hello " +  task.request.headers['host']

It works, but weird hellohost.delay (). get () hangs on the client, any ideas why?

+4
1

. . .

0

Source: https://habr.com/ru/post/1526749/


All Articles