Getting task_id in Celery task

This is probably a dumb question, but it made me focus on the Ruby background.

I have an object that looks like this when I try to print it.

print celery.AsyncResult.task_id >>><property object at 0x10c383838> 

I was expecting the actual value of the task_id property to be printed here. How can I get the actual value?

UPDATE 1

 @celery.task def scan(host): print celery.AsyncResult.task_id cmd = 'ps -ef' cm = shlex.split(cmd) scan = subprocess.check_output(cm) return scan 

Best wishes.

+10
python object celery
source share
3 answers
+15
source share

You access property from the class, while task_id is a property of AsyncResult instances.

To get the task_id value, you must first create an instance of this class, after which access to async_result_instance.task_id will return the real identifier to you.

In your updated code:

 @celery.task def scan(host): print celery.AsyncResult.task_id # ... 

Here you get access to the class, as I already explained. What you want is an instance of the current task. You can use celery.current_task to get the current task executable:

 @celery.task def scan(host): print celery.current_task.task_id 

Or, if you are interested in a unique identifier, use the request attribute of the decorated function:

 @celery.task def scan(host): print scan.request.id cmd = 'ps -ef' cm = shlex.split(cmd) # IMPORTANT: Do *not* use "scan = ..."! result = subprocess.check_output(cm) return result 

In the second case, do not use any local variable named scan , otherwise you will get an UnboundLocalError .

(The code is not verified, as I have not installed celery .)


property are descriptors used to provide attribute access to get / set methods, so you can access data such as:

 instance.attribute instance.attribute = value 

But when the code is executed, the installer or the receiver can control what is happening.

You can verify this with a dummy class:

 >>> class Dummy(object): ... @property ... def a(self): ... print("called the getter!") ... return 1 ... >>> Dummy.a <property object at 0x7fdae86978e8> >>> Dummy().a called the getter! 1 
+13
source share

To make your tasks more "OO-like", you can use the bind argument to get a reference to self :

 @celery.task(bind=True) def scan(self, host): print self.request.id 

Note that self.request.id is actually an instance of AsyncTask . That the task identifier was as a string , you should do self.request.id.__str__() .

From the Celery Documentation (after the example):

The bind argument means that the function will be a β€œbound method” so that you can access the attributes and methods of the instance of the task type.

+11
source share

All Articles