Alok
Alok

Reputation: 10624

Bound task in celery is not able to access instance variable in django project

I have setup celery in my django project using official documentation at http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html#using-celery-with-django

So my MyApp/tasks.py have content

from celery import shared_task

class Someclass():
    def __init__(self, x, y):
        self.x = x
        self.y = y

    @shared_task(bind=True) 
    def func1(self):
        '''This does not work'''
        return self.x + self.y


    @shared_task(bind=True)
    def func2(self, a, b):
        '''This works well'''
        return a + b

When I run

In [9]: o = Someclass(3, 4)    
In [10]: o.func1.delay()
Out[10]: <AsyncResult: afc6b151-d71c-4f46-a916-6917f98c681f>

I get the error

AttributeError: 'func1' object has no attribute 'x'

When I run

In [11]: o.func2.delay(3, 4)
Out[11]: <AsyncResult: 3b227f00-8d9c-472b-b7d8-8b4b6261f689>

This works perfectly

How can I make func1 working so that it can use instance variables e.g. x and y?

Upvotes: 0

Views: 617

Answers (1)

Sergey Pugach
Sergey Pugach

Reputation: 5669

from celery import shared_task

@shared_task(bind=True)
def func(self, a, b):
    return a + b


class Someclass():
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def func1(self):
        return func.delay(self.x, self.y)

Upvotes: 1

Related Questions