Reputation: 6765
When defining a celery task function using the @task
decorator, is it possible to add some extra attributes to the decorator that I can access from my task base class when the task starts without adding new parameters to the task function itself?
Something like
class CustomBase(celery.Task):
def __call__(self, *args, **kwargs):
# do something with foo
...
self.run()
@task(base=CustomBase, bind=True, foo=123)
def add(self, x, y):
return x + y
Upvotes: 3
Views: 1422
Reputation: 2167
If you pass some variables to the task decorator(with bind=True) it will passes them to the constructor of the Task. and you can access them using self. Just an example of code
from celery import Celery, chord, chain, Task
backend = 'redis://redis:6379/'
app = Celery(result_backend=backend, backend=backend)
class CustomBase(Task):
def __call__(self, *args, **kwargs):
print(self.foo) # in class
return super().__call__(*args, **kwargs)
@app.task(base=CustomBase, bind=True, foo=123)
def add(self, x, y):
print(self.foo) # in task
return x + y
add.apply_async((1, 2))
Upvotes: 5