Python Celery - 获取当前任务的任务 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3302320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Celery - Get task id for current task
提问by mattbasta
How can I get the task_id value for a task from within the task? Here's my code:
如何从任务中获取任务的 task_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)
The idea is that when I create a new instance of the task, I retrieve the task_idfrom the task object. I then use the task id to determine whether the task has completed. I don'twant to keep track of the task by the pathvalue because the file is "cleaned up" after the task completes, and may or may not exist.
这个想法是,当我创建任务的新实例时,我task_id从任务对象中检索。然后我使用任务 id 来确定任务是否已完成。我不想通过path值跟踪任务,因为文件在任务完成后被“清理”,并且可能存在也可能不存在。
In the above example, how would I get the value of current_task_id?
在上面的例子中,我将如何获得 的值current_task_id?
采纳答案by asksol
Celery does set some default keyword arguments if the task accepts them. (you can accept them by either using **kwargs, or list them specifically)
如果任务接受它们,Celery 会设置一些默认的关键字参数。(您可以使用 **kwargs 接受它们,也可以具体列出它们)
@task
def do_job(path, task_id=None):
cache.set(task_id, operation_results)
The list of default keyword arguments is documented here: http://ask.github.com/celery/userguide/tasks.html#default-keyword-arguments
默认关键字参数列表记录在此处:http: //ask.github.com/celery/userguide/tasks.html#default-keyword-arguments
回答by Alex Lokk
Since Celery 2.2.0, information related to the currently executed task is saved to task.request(it's called ?the context?). So you should get task id from this context (not from keyword arguments, which are deprecated):
从 Celery 2.2.0 开始,与当前执行的任务相关的信息被保存到task.request(它被称为?上下文?)。所以你应该从这个上下文中获取任务 id(而不是从不推荐使用的关键字参数中获取):
@task
def do_job(path):
cache.set(do_job.request.id, operation_results)
The list of all available fields is documented here: http://celery.readthedocs.org/en/latest/userguide/tasks.html?highlight=requestcontext#context
此处记录了所有可用字段的列表:http: //celery.readthedocs.org/en/latest/userguide/tasks.html?highlight=requestcontext#context

