芹菜-获取当前助教的任务id

2024-05-23 17:01:11 发布

您现在位置:Python中文网/ 问答频道 /正文

如何从任务中获取任务的任务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_id。然后使用任务id来确定任务是否已完成。我不想用path值跟踪任务,因为文件在任务完成后被“清理”,可能存在,也可能不存在。

在上面的示例中,如何获取current_task_id的值?


Tags: pathdjango代码fromcoreimportdecoratorsid
3条回答

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

@task
def do_job(path, task_id=None):
    cache.set(task_id, operation_results)

默认关键字参数的列表如下所示: http://ask.github.com/celery/userguide/tasks.html#default-keyword-arguments

由于芹菜2.2.0,与当前执行的任务相关的信息被保存到task.request(它被称为“上下文”)。因此,您应该从此上下文(而不是从关键字参数(已弃用)获取任务id:

@task
def do_job(path):
    cache.set(do_job.request.id, operation_results)

此处记录了所有可用字段的列表: http://celery.readthedocs.org/en/latest/userguide/tasks.html?highlight=requestcontext#context

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

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

相关问题 更多 >