代码之家  ›  专栏  ›  技术社区  ›  Luv33preet

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

  •  4
  • Luv33preet  · 技术社区  · 6 年前

    @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

    1 回复  |  直到 6 年前
        1
  •  13
  •   sytech    6 年前

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

    假设你有一个标准的任务 add

    @shared_task
    def add(x, y):
        return x + y
    

    如果您指定 在这个任务上,它需要接受另一个论点。

    @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):