【问题标题】:django-celery: bind=True fails, takes 2 positional arguments but 3 were givendjango-celery:bind=True 失败,接受 2 个位置参数,但给出了 3 个
【发布时间】:2018-12-24 23:03:41
【问题描述】:

如果失败,我正在尝试重试 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

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

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

使用 Django2.0.5 和 celery4.2.0

【问题讨论】:

    标签: python django django-celery


    【解决方案1】:

    您必须添加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):
    

    【讨论】:

    • 又救了我的狗。
    猜你喜欢
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 2022-01-17
    • 2019-09-21
    • 2019-07-19
    • 2021-02-02
    相关资源
    最近更新 更多