Question

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?

Était-ce utile?

La solution

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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top