问题
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