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

Luv*_*eet 7 django python-3.x django-celery

如果 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)
Run Code Online (Sandbox Code Playgroud)

但是在调用此任务时出现此错误,

TypeError: update_station_es_index() takes 2 positional arguments but 3 were given
Run Code Online (Sandbox Code Playgroud)

我没有在网上找到足够的帮助来解决这个错误,只是这个 github 问题,但这并不能解释太多。

谁能告诉我发生了什么以及这里的解决方案是什么?

使用 Django2.0.5 和 celery4.2.0

syt*_*ech 16

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

假设您有一个标准任务add,它需要两个参数

@shared_task
def add(x, y):
    return x + y
Run Code Online (Sandbox Code Playgroud)

如果您bind=True在此任务上指定,则需要接受另一个参数。

@shared_task(bind=True)
def add(self, x, y):
    # ...
Run Code Online (Sandbox Code Playgroud)

所以改变

def update_station_es_index(doc_id, doc_body):
Run Code Online (Sandbox Code Playgroud)

def update_station_es_index(self, doc_id, doc_body):
Run Code Online (Sandbox Code Playgroud)