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

倖福魔咒の 提交于 2019-12-03 16:38:47

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/6180843/avoid-recursive-save-when-using-celery-to-update-django-model-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!