I was just wondering what the proper way to pass an argument to a custom task decorator would be. For example, I found out I can subclass a celery task as follows:
class MyTask(celery.Task):
def __init__(self):
# some custom stuff here
super(MyTask, self).__init__()
def __call__(self, *args, **kwargs):
# do some custom stuff here
res = self.run(*args, **kwargs)
# do some more stuff here
return res
and use it as below:
@MyTask
def add(x, y):
return x + y
but I would like to be able to pass an argument to this task and have it behave differently based on the argument (or equivalently, based on the function it is decorating). There are two methods I can think of doing this. One is by passing an additional kwarg to celery's task wrapper and specifying the base explicitly, such as
@celery.task(base=MyTask, foo="bar")
def add(x, y):
return x + y
which I can access in my custom task as self.foo
, but this feels a bit like cheating to me. The other way would be to inspect self.task
, and change the behaviour based on its value, but this also seems like overkill. Ideally I would like to pass the kwarg directly to the custom task class,
@MyTask(foo="bar")
def add(x, y):
return x + y
but of course this creates an instance of MyTask
, which we do not want and will not work anyhow.
Any suggestions on the proper way of doing this?