Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if Django function is running in a celery worker

I have a post_save hook that triggers a task to run in celery. The task also updates the model, which causes the post_save hook to run. The catch is I do not want to .delay() the call in this instance, I just want to run it synchronously because it's already being run in a worker.

Is there an environmental variable or something else I can use to detect when the code is being run in celery?

To clarify: I'm aware that Celery tasks can still be called as normal functions, that's exactly what I'm trying to take advantage of. I want to do something like this:

if os.environ['is_celery']:
    my_task(1, 2, 3)
else:
    my_task.delay(1, 2, 3)
like image 914
Luke Sapan Avatar asked Sep 17 '25 14:09

Luke Sapan


1 Answers

Usually you'd have common.py, production.py, test.py and local.py/dev.py. You could just add a celery_settings.py with the following content:

from production import *
IS_CELERY = True

Then in your celery.py (I'm assuming you have one) you'll do

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.celery_settings")

Then in your script you can now do:

if getattr(settings, 'IS_CELERY', None):
    my_task(1, 2, 3)
else:
    my_task.delay(1, 2, 3)
like image 149
domino Avatar answered Sep 19 '25 06:09

domino