Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Celery: When and where to use the return value of a .delay() running @task to update DB?

I am building a Django app with Celery.

I have a @task which I fire with .delay().

Once the task is complete, I need to use the return value (a string) to update my Postgres DB.

I am not sure where should I put the DB update code?

Do I do:

a)

return_value = my_task.delay(..)
(ORM - DB update code)

b)

my_task.delay(..) # <-- Task updates the DB.

Which is the Pythonic correct way here?

like image 374
Phil Avatar asked Jan 10 '23 18:01

Phil


1 Answers

You should use the second approach since delay method exits right away without waiting for your task to finish. And the return_value variable will be AsyncResult instance, not the value you wanted to return from my_task. So if you want to update the DB once the task is complete, do it inside the task.

Alternatively you could use on_success handler of the Task class:

class MyTask(Task):

    def run(self, *args, **kwargs):
        # your task execution code

    def on_success(self, retval, task_id, args, kwargs):
        # put the retval into the DB
like image 155
isobolev Avatar answered Jan 19 '23 00:01

isobolev