| 1 |
.. _django-first-steps: |
| 2 |
|
| 3 |
========================= |
| 4 |
First steps with Django |
| 5 |
========================= |
| 6 |
|
| 7 |
Using Celery with Django |
| 8 |
======================== |
| 9 |
|
| 10 |
.. note:: |
| 11 |
|
| 12 |
Previous versions of Celery required a separate library to work with Django, |
| 13 |
but since 3.1 this is no longer the case. Django is supported out of the |
| 14 |
box now so this document only contains a basic way to integrate Celery and |
| 15 |
Django. You'll use the same API as non-Django users so you're recommended |
| 16 |
to read the :ref:`first-steps` tutorial |
| 17 |
first and come back to this tutorial. When you have a working example you can |
| 18 |
continue to the :ref:`next-steps` guide. |
| 19 |
|
| 20 |
.. note:: |
| 21 |
|
| 22 |
Celery 5.5.x supports Django 2.2 LTS or newer versions. |
| 23 |
Please use Celery 5.2.x for versions older than Django 2.2 or Celery 4.4.x if your Django version is older than 1.11. |
| 24 |
|
| 25 |
To use Celery with your Django project you must first define |
| 26 |
an instance of the Celery library (called an "app") |
| 27 |
|
| 28 |
If you have a modern Django project layout like:: |
| 29 |
|
| 30 |
- proj/ |
| 31 |
- manage.py |
| 32 |
- proj/ |
| 33 |
- __init__.py |
| 34 |
- settings.py |
| 35 |
- urls.py |
| 36 |
|
| 37 |
then the recommended way is to create a new `proj/proj/celery.py` module |
| 38 |
that defines the Celery instance: |
| 39 |
|
| 40 |
:file: `proj/proj/celery.py` |
| 41 |
|
| 42 |
.. literalinclude:: ../../examples/django/proj/celery.py |
| 43 |
|
| 44 |
Then you need to import this app in your :file:`proj/proj/__init__.py` |
| 45 |
module. This ensures that the app is loaded when Django starts |
| 46 |
so that the ``@shared_task`` decorator (mentioned later) will use it: |
| 47 |
|
| 48 |
:file:`proj/proj/__init__.py`: |
| 49 |
|
| 50 |
.. literalinclude:: ../../examples/django/proj/__init__.py |
| 51 |
|
| 52 |
Note that this example project layout is suitable for larger projects, |
| 53 |
for simple projects you may use a single contained module that defines |
| 54 |
both the app and tasks, like in the :ref:`tut-celery` tutorial. |
| 55 |
|
| 56 |
Let's break down what happens in the first module, |
| 57 |
first, we set the default :envvar:`DJANGO_SETTINGS_MODULE` environment |
| 58 |
variable for the :program:`celery` command-line program: |
| 59 |
|
| 60 |
.. code-block:: python |
| 61 |
|
| 62 |
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') |
| 63 |
|
| 64 |
You don't need this line, but it saves you from always passing in the |
| 65 |
settings module to the ``celery`` program. It must always come before |
| 66 |
creating the app instances, as is what we do next: |
| 67 |
|
| 68 |
.. code-block:: python |
| 69 |
|
| 70 |
app = Celery('proj') |
| 71 |
|
| 72 |
This is our instance of the library, you can have many instances |
| 73 |
but there's probably no reason for that when using Django. |
| 74 |
|
| 75 |
We also add the Django settings module as a configuration source |
| 76 |
for Celery. This means that you don't have to use multiple |
| 77 |
configuration files, and instead configure Celery directly |
| 78 |
from the Django settings; but you can also separate them if wanted. |
| 79 |
|
| 80 |
.. code-block:: python |
| 81 |
|
| 82 |
app.config_from_object('django.conf:settings', namespace='CELERY') |
| 83 |
|
| 84 |
The uppercase name-space means that all |
| 85 |
:ref:`Celery configuration options <configuration>` |
| 86 |
must be specified in uppercase instead of lowercase, and start with |
| 87 |
``CELERY_``, so for example the :setting:`task_always_eager` setting |
| 88 |
becomes ``CELERY_TASK_ALWAYS_EAGER``, and the :setting:`broker_url` |
| 89 |
setting becomes ``CELERY_BROKER_URL``. This also applies to the |
| 90 |
workers settings, for instance, the :setting:`worker_concurrency` |
| 91 |
setting becomes ``CELERY_WORKER_CONCURRENCY``. |
| 92 |
|
| 93 |
For example, a Django project's configuration file might include: |
| 94 |
|
| 95 |
.. code-block:: python |
| 96 |
:caption: settings.py |
| 97 |
|
| 98 |
... |
| 99 |
|
| 100 |
# Celery Configuration Options |
| 101 |
CELERY_TIMEZONE = "Australia/Tasmania" |
| 102 |
CELERY_TASK_TRACK_STARTED = True |
| 103 |
CELERY_TASK_TIME_LIMIT = 30 * 60 |
| 104 |
|
| 105 |
You can pass the settings object directly instead, but using a string |
| 106 |
is better since then the worker doesn't have to serialize the object. |
| 107 |
The ``CELERY_`` namespace is also optional, but recommended (to |
| 108 |
prevent overlap with other Django settings). |
| 109 |
|
| 110 |
Next, a common practice for reusable apps is to define all tasks |
| 111 |
in a separate ``tasks.py`` module, and Celery does have a way to |
| 112 |
auto-discover these modules: |
| 113 |
|
| 114 |
.. code-block:: python |
| 115 |
|
| 116 |
app.autodiscover_tasks() |
| 117 |
|
| 118 |
With the line above Celery will automatically discover tasks from all |
| 119 |
of your installed apps, following the ``tasks.py`` convention:: |
| 120 |
|
| 121 |
- app1/ |
| 122 |
- tasks.py |
| 123 |
- models.py |
| 124 |
- app2/ |
| 125 |
- tasks.py |
| 126 |
- models.py |
| 127 |
|
| 128 |
|
| 129 |
This way you don't have to manually add the individual modules |
| 130 |
to the :setting:`CELERY_IMPORTS <imports>` setting. |
| 131 |
|
| 132 |
Finally, the ``debug_task`` example is a task that dumps |
| 133 |
its own request information. This is using the new ``bind=True`` task option |
| 134 |
introduced in Celery 3.1 to easily refer to the current task instance. |
| 135 |
|
| 136 |
Using the ``@shared_task`` decorator |
| 137 |
------------------------------------ |
| 138 |
|
| 139 |
The tasks you write will probably live in reusable apps, and reusable |
| 140 |
apps cannot depend on the project itself, so you also cannot import your app |
| 141 |
instance directly. |
| 142 |
|
| 143 |
The ``@shared_task`` decorator lets you create tasks without having any |
| 144 |
concrete app instance: |
| 145 |
|
| 146 |
:file:`demoapp/tasks.py`: |
| 147 |
|
| 148 |
.. literalinclude:: ../../examples/django/demoapp/tasks.py |
| 149 |
|
| 150 |
|
| 151 |
.. seealso:: |
| 152 |
|
| 153 |
You can find the full source code for the Django example project at: |
| 154 |
https://github.com/celery/celery/tree/main/examples/django/ |
| 155 |
|
| 156 |
Trigger tasks at the end of the database transaction |
| 157 |
---------------------------------------------------- |
| 158 |
|
| 159 |
A common pitfall with Django is triggering a task immediately and not wait until |
| 160 |
the end of the database transaction, which means that the Celery task may run |
| 161 |
before all changes are persisted to the database. For example: |
| 162 |
|
| 163 |
.. code-block:: python |
| 164 |
|
| 165 |
# views.py |
| 166 |
def create_user(request): |
| 167 |
# Note: simplified example, use a form to validate input |
| 168 |
user = User.objects.create(username=request.POST['username']) |
| 169 |
send_email.delay(user.pk) |
| 170 |
return HttpResponse('User created') |
| 171 |
|
| 172 |
# task.py |
| 173 |
@shared_task |
| 174 |
def send_email(user_pk): |
| 175 |
user = User.objects.get(pk=user_pk) |
| 176 |
# send email ... |
| 177 |
|
| 178 |
In this case, the ``send_email`` task could start before the view has committed |
| 179 |
the transaction to the database, and therefore the task may not be able to find |
| 180 |
the user. |
| 181 |
|
| 182 |
A common solution is to use Django's `on_commit`_ hook to trigger the task |
| 183 |
after the transaction has been committed: |
| 184 |
|
| 185 |
.. _on_commit: https://docs.djangoproject.com/en/stable/topics/db/transactions/#django.db.transaction.on_commit |
| 186 |
|
| 187 |
.. code-block:: diff |
| 188 |
|
| 189 |
- send_email.delay(user.pk) |
| 190 |
+ transaction.on_commit(lambda: send_email.delay(user.pk)) |
| 191 |
|
| 192 |
.. versionadded:: 5.4 |
| 193 |
|
| 194 |
Since this is such a common pattern, Celery 5.4 introduced a handy shortcut for this, |
| 195 |
using a :class:`~celery.contrib.django.task.DjangoTask`. Instead of calling |
| 196 |
:meth:`~celery.app.task.Task.delay`, you should call |
| 197 |
:meth:`~celery.contrib.django.task.DjangoTask.delay_on_commit`: |
| 198 |
|
| 199 |
.. code-block:: diff |
| 200 |
|
| 201 |
- send_email.delay(user.pk) |
| 202 |
+ send_email.delay_on_commit(user.pk) |
| 203 |
|
| 204 |
|
| 205 |
This API takes care of wrapping the call into the `on_commit`_ hook for you. |
| 206 |
In rare cases where you want to trigger a task without waiting, the existing |
| 207 |
:meth:`~celery.app.task.Task.delay` API is still available. |
| 208 |
|
| 209 |
One key difference compared to the ``delay`` method, is that ``delay_on_commit`` |
| 210 |
will NOT return the task ID back to the caller. The task is not sent to the broker |
| 211 |
when you call the method, only when the Django transaction finishes. If you need the |
| 212 |
task ID, best to stick to :meth:`~celery.app.task.Task.delay`. |
| 213 |
|
| 214 |
This task class should be used automatically if you've follow the setup steps above. |
| 215 |
However, if your app :ref:`uses a custom task base class <task-custom-classes>`, |
| 216 |
you'll need inherit from :class:`~celery.contrib.django.task.DjangoTask` instead of |
| 217 |
:class:`~celery.app.task.Task` to get this behaviour. |
| 218 |
|
| 219 |
Django Connection pool |
| 220 |
---------------------- |
| 221 |
From Django 5.1+ there is built-in support for database connection pooling. |
| 222 |
If you enable it in Django ``DATABASES`` settings Celery will automatically |
| 223 |
handle connection pool closing in worker processes via ``close_pool`` |
| 224 |
database backend method as |
| 225 |
`sharing connections across processes is not possible. <https://github.com/psycopg/psycopg/issues/544#issuecomment-1500886864>`_ |
| 226 |
|
| 227 |
You can find more about Connection pool at `Django docs. <https://docs.djangoproject.com/en/dev/ref/databases/#connection-pool>`_ |
| 228 |
|
| 229 |
Extensions |
| 230 |
========== |
| 231 |
|
| 232 |
.. _django-celery-results: |
| 233 |
|
| 234 |
``django-celery-results`` - Using the Django ORM/Cache as a result backend |
| 235 |
-------------------------------------------------------------------------- |
| 236 |
|
| 237 |
The :pypi:`django-celery-results` extension provides result backends |
| 238 |
using either the Django ORM, or the Django Cache framework. |
| 239 |
|
| 240 |
To use this with your project you need to follow these steps: |
| 241 |
|
| 242 |
#. Install the :pypi:`django-celery-results` library: |
| 243 |
|
| 244 |
.. code-block:: console |
| 245 |
|
| 246 |
$ pip install django-celery-results |
| 247 |
|
| 248 |
#. Add ``django_celery_results`` to ``INSTALLED_APPS`` in your |
| 249 |
Django project's :file:`settings.py`:: |
| 250 |
|
| 251 |
INSTALLED_APPS = ( |
| 252 |
..., |
| 253 |
'django_celery_results', |
| 254 |
) |
| 255 |
|
| 256 |
Note that there is no dash in the module name, only underscores. |
| 257 |
|
| 258 |
#. Create the Celery database tables by performing a database migrations: |
| 259 |
|
| 260 |
.. code-block:: console |
| 261 |
|
| 262 |
$ python manage.py migrate django_celery_results |
| 263 |
|
| 264 |
#. Configure Celery to use the :pypi:`django-celery-results` backend. |
| 265 |
|
| 266 |
Assuming you are using Django's :file:`settings.py` to also configure |
| 267 |
Celery, add the following settings: |
| 268 |
|
| 269 |
.. code-block:: python |
| 270 |
|
| 271 |
CELERY_RESULT_BACKEND = 'django-db' |
| 272 |
|
| 273 |
When using the cache backend, you can specify a cache defined within |
| 274 |
Django's CACHES setting. |
| 275 |
|
| 276 |
.. code-block:: python |
| 277 |
|
| 278 |
CELERY_RESULT_BACKEND = 'django-cache' |
| 279 |
|
| 280 |
# pick which cache from the CACHES setting. |
| 281 |
CELERY_CACHE_BACKEND = 'default' |
| 282 |
|
| 283 |
# django setting. |
| 284 |
CACHES = { |
| 285 |
'default': { |
| 286 |
'BACKEND': 'django.core.cache.backends.db.DatabaseCache', |
| 287 |
'LOCATION': 'my_cache_table', |
| 288 |
} |
| 289 |
} |
| 290 |
|
| 291 |
For additional configuration options, view the |
| 292 |
:ref:`conf-result-backend` reference. |
| 293 |
|
| 294 |
|
| 295 |
``django-celery-beat`` - Database-backed Periodic Tasks with Admin interface. |
| 296 |
----------------------------------------------------------------------------- |
| 297 |
|
| 298 |
See :ref:`beat-custom-schedulers` for more information. |
| 299 |
|
| 300 |
Starting the worker process |
| 301 |
=========================== |
| 302 |
|
| 303 |
In a production environment you'll want to run the worker in the background |
| 304 |
as a daemon - see :ref:`daemonizing` - but for testing and |
| 305 |
development it is useful to be able to start a worker instance by using the |
| 306 |
:program:`celery worker` manage command, much as you'd use Django's |
| 307 |
:command:`manage.py runserver`: |
| 308 |
|
| 309 |
.. code-block:: console |
| 310 |
|
| 311 |
$ celery -A proj worker -l INFO |
| 312 |
|
| 313 |
For a complete listing of the command-line options available, |
| 314 |
use the help command: |
| 315 |
|
| 316 |
.. code-block:: console |
| 317 |
|
| 318 |
$ celery --help |
| 319 |
|
| 320 |
Where to go from here |
| 321 |
===================== |
| 322 |
|
| 323 |
If you want to learn more you should continue to the |
| 324 |
:ref:`Next Steps <next-steps>` tutorial, and after that you |
| 325 |
can study the :ref:`User Guide <guide>`. |