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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With