我正在覆盖模型的save()方法以使用Celery调用异步任务。该任务还保存了模型,因此我最终得到了重复调用Celery任务的递归情况。这是代码:
模特的保存方法:
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任务:
from celery.decorators import task
@task()
def get_elevation_data(route):
...
route.elevation_data = results
route.save()
如何避免这种递归?
答案 0 :(得分:14)
添加一个关键字参数,告诉save不要递归:
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)
然后:
from celery.decorators import task
@task()
def get_elevation_data(route):
...
route.elevation_data = results
route.save(elevation_data=False)