django-celery: bind=True 失败,需要2个位置参数但传入了3个。

14

我正在尝试在celery任务失败时进行重试。这是我的任务:

@shared_task(queue='es', bind=True, max_retries=3)
def update_station_es_index(doc_id, doc_body):
    """
    Celery consumer method for updating ES.
    """
    try:
        #es_client is connecting to ElasticSearch
        es_client.update_stations(id=doc_id, body=doc_body)
    except Exception as e:
        self.retry(exc=e)

但是当调用此任务时,我会收到此错误:

TypeError: update_station_es_index() takes 2 positional arguments but 3 were given

我在网络上没有找到关于这个错误的足够帮助,只有这个 github 问题,但那并没有解释太多。

有人能告诉我这里发生了什么以及解决方案是什么吗?

使用 Django2.0.5 和 celery4.2.0

1个回答

27

你必须将self作为一个参数添加进来。当你指定bind=True时,任务本身将作为第一个参数传递。

假设你有一个接收两个参数的标准任务add

@shared_task
def add(x, y):
    return x + y
如果您在此任务上指定了bind=True,它将需要接受另一个参数。
@shared_task(bind=True)
def add(self, x, y):
    # ...

所以改变

def update_station_es_index(doc_id, doc_body):
def update_station_es_index(self, doc_id, doc_body):

又一次拯救了我的屁股。 - unlockme
哪个选项更好,使用(bind=True)还是不使用? - Talha Anwar
@TalhaAnwar 这是情境性的... 当你需要引用任务对象时,请使用 bind=True。如果你不需要引用任务,则可以省略 bind=True - sytech

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接