Detect if Django function is running in a celery worker
<p>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 <code>.delay()</code> the call in this instance, I just want to run it synchronously because it's already being run in a worker.</p>

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

<p>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:</p>

<pre><code>if os.environ['is_celery']:
    my_task(1, 2, 3)
else:
    my_task.delay(1, 2, 3)
</code></pre>

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

<pre><code>from production import *
IS_CELERY = True
</code></pre>

<p>Then in your <code>celery.py</code> (I'm assuming you have one) you'll do</p>

<pre><code>os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.celery_settings")
</code></pre>

<p>Then in your script you can now do:</p>

<pre><code>if getattr(settings, 'IS_CELERY', None):
    my_task(1, 2, 3)
else:
    my_task.delay(1, 2, 3)
</code></pre>

python django celery