Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid recursive save() when using celery to update Django model fields

I'm overriding a model's save() method to call an asynchronous task with Celery. That task also saves the model, and so I end up with a recursive situation where the Celery task gets called repeatedly. Here's the code:

Model's save method:

def save(self, *args, **kwargs):
    super(Route, self).save(*args, **kwargs)
    from .tasks import get_elevation_data
    get_elevation_data.delay(self)

get_elevation_data task:

from celery.decorators import task

@task()
def get_elevation_data(route):
    ...
    route.elevation_data = results
    route.save()

How can I avoid this recursion?

like image 573
worksology Avatar asked May 30 '11 21:05

worksology


1 Answers

Add a keyword argument that tells save not to recurse:

 def save(self, elevation_data=True, *args, **kwargs):
   super(Route, self).save(*args, **kwargs)
   if elevation_data:
     from .tasks import get_elevation_data
     get_elevation_data.delay(self)

And then:

 from celery.decorators import task

 @task()
 def get_elevation_data(route):
     ...
     route.elevation_data = results
     route.save(elevation_data=False)
like image 75
Tim Yates Avatar answered Oct 08 '22 22:10

Tim Yates