Python 芹菜-获取当前任务的任务id

Python 芹菜-获取当前任务的任务id,python,django,celery,Python,Django,Celery,如何从任务中获取任务的任务id值?这是我的密码: from celery.decorators import task from django.core.cache import cache @task def do_job(path): "Performs an operation on a file" # ... Code to perform the operation ... cache.set(current_task_id, operation_resu

如何从任务中获取任务的任务id值?这是我的密码:

from celery.decorators import task
from django.core.cache import cache

@task
def do_job(path):
    "Performs an operation on a file"

    # ... Code to perform the operation ...

    cache.set(current_task_id, operation_results)
其思想是,当我创建任务的新实例时,我从任务对象中检索
task\u id
。然后,我使用任务id来确定任务是否已完成。我不想通过
路径
值跟踪任务,因为文件在任务完成后被“清理”,可能存在,也可能不存在


在上面的示例中,如何获取当前任务id的值?

如果任务接受,芹菜会设置一些默认关键字参数。 (您可以使用**kwargs接受,也可以具体列出)

此处记录了默认关键字参数列表:

自芹菜2.2.0以来,与当前执行的任务相关的信息被保存到
task.request
(称为«上下文»)。因此,您应该从该上下文中获取任务id(而不是从不推荐使用的关键字参数):

此处记录了所有可用字段的列表:

从芹菜3.1开始,您可以使用decorator参数,并可以访问当前请求:

@task(bind=True)
def do_job(self, path):
    cache.set(self.request.id, operation_results)

从Celery 2.2.0开始,此id已被弃用(请参阅下面的答案)。您能在任务之外获取此id吗?例如,运行任务,获取id并使用此id检查任务是否完成。是的,您可以从AsyncResult获取id,然后根据id重新创建AsyncResult,如果您有芹菜3+,请使用Balthazar的答案检查文档。这更清楚明了。谢谢你的新回复。它的工作原理像一个charmIs,也可以知道它是否是一个周期性的任务?
@task
def do_job(path):
    cache.set(do_job.request.id, operation_results)
@task(bind=True)
def do_job(self, path):
    cache.set(self.request.id, operation_results)