How to get Task ID in celery django from the currently running Shared Task itself?

偶尔善良 提交于 2019-12-13 20:10:04

问题


In my views.py I am using celery to run a shared task present in tasks.py.

Here is how I call from views.py

task = task_addnums.delay()
task_id = task.id

tasks.py looks as

from celery import shared_task
from celery.result import AsyncResult


@shared_task
def task_addnums():
   # print self.request.id
   # do something
    return True

Now, as we can see we already have task_id from task.id in views.py . But, Let's say If I want to fetch task id from the shared_task itself how can I ? The goal is to get task id from the task_addnums itself so I can use that to pass into some other function. I tried using self.request.id considering the first param is self . But it didn't worked.


回答1:


Solved.

This answer is a gem Getting task_id inside a Celery task

You can do function_name.request.id to get task id.




回答2:


current_task from celery will get the current task.Code like this:

from celery import shared_task, current_task

@shared_task
def task_addnums():
    print(current_task.request)
    # do something
    return True


来源:https://stackoverflow.com/questions/50915758/how-to-get-task-id-in-celery-django-from-the-currently-running-shared-task-itsel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!