first-steps-with-django.rst 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. .. _django-first-steps:
  2. =========================
  3. First steps with Django
  4. =========================
  5. Using Celery with Django
  6. ========================
  7. .. note::
  8. Previous versions of Celery required a separate library to work with Django,
  9. but since 3.1 this is no longer the case. Django is supported out of the
  10. box now so this document only contains a basic way to integrate Celery and
  11. Django. You'll use the same API as non-Django users so you're recommended
  12. to read the :ref:`first-steps` tutorial
  13. first and come back to this tutorial. When you have a working example you can
  14. continue to the :ref:`next-steps` guide.
  15. .. note::
  16. Celery 4.0 supports Django 1.8 and newer versions. Please use Celery 3.1
  17. for versions older than Django 1.8.
  18. To use Celery with your Django project you must first define
  19. an instance of the Celery library (called an "app")
  20. If you have a modern Django project layout like::
  21. - proj/
  22. - manage.py
  23. - proj/
  24. - __init__.py
  25. - settings.py
  26. - urls.py
  27. then the recommended way is to create a new `proj/proj/celery.py` module
  28. that defines the Celery instance:
  29. :file: `proj/proj/celery.py`
  30. .. literalinclude:: ../../examples/django/proj/celery.py
  31. Then you need to import this app in your :file:`proj/proj/__init__.py`
  32. module. This ensures that the app is loaded when Django starts
  33. so that the ``@shared_task`` decorator (mentioned later) will use it:
  34. :file:`proj/proj/__init__.py`:
  35. .. literalinclude:: ../../examples/django/proj/__init__.py
  36. Note that this example project layout is suitable for larger projects,
  37. for simple projects you may use a single contained module that defines
  38. both the app and tasks, like in the :ref:`tut-celery` tutorial.
  39. Let's break down what happens in the first module,
  40. first we import absolute imports from the future, so that our
  41. ``celery.py`` module won't clash with the library:
  42. .. code-block:: python
  43. from __future__ import absolute_import
  44. Then we set the default :envvar:`DJANGO_SETTINGS_MODULE` environment variable
  45. for the :program:`celery` command-line program:
  46. .. code-block:: python
  47. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')
  48. You don't need this line, but it saves you from always passing in the
  49. settings module to the ``celery`` program. It must always come before
  50. creating the app instances, as is what we do next:
  51. .. code-block:: python
  52. app = Celery('proj')
  53. This is our instance of the library, you can have many instances
  54. but there's probably no reason for that when using Django.
  55. We also add the Django settings module as a configuration source
  56. for Celery. This means that you don't have to use multiple
  57. configuration files, and instead configure Celery directly
  58. from the Django settings; but you can also separate them if wanted.
  59. .. code-block:: python
  60. app.config_from_object('django.conf:settings', namespace='CELERY')
  61. The uppercase name-space means that all Celery configuration options
  62. must be specified in uppercase instead of lowercase, and start with
  63. ``CELERY_``, so for example the :setting:`task_always_eager` setting
  64. becomes ``CELERY_TASK_ALWAYS_EAGER``, and the :setting:`broker_url`
  65. setting becomes ``CELERY_BROKER_URL``.
  66. You can pass the settings object directly instead, but using a string
  67. is better since then the worker doesn't have to serialize the object.
  68. The ``CELERY_`` namespace is also optional, but recommended (to
  69. prevent overlap with other Django settings).
  70. Next, a common practice for reusable apps is to define all tasks
  71. in a separate ``tasks.py`` module, and Celery does have a way to
  72. auto-discover these modules:
  73. .. code-block:: python
  74. app.autodiscover_tasks()
  75. With the line above Celery will automatically discover tasks from all
  76. of your installed apps, following the ``tasks.py`` convention::
  77. - app1/
  78. - tasks.py
  79. - models.py
  80. - app2/
  81. - tasks.py
  82. - models.py
  83. This way you don't have to manually add the individual modules
  84. to the :setting:`CELERY_IMPORTS <imports>` setting.
  85. Finally, the ``debug_task`` example is a task that dumps
  86. its own request information. This is using the new ``bind=True`` task option
  87. introduced in Celery 3.1 to easily refer to the current task instance.
  88. Using the ``@shared_task`` decorator
  89. ------------------------------------
  90. The tasks you write will probably live in reusable apps, and reusable
  91. apps cannot depend on the project itself, so you also cannot import your app
  92. instance directly.
  93. The ``@shared_task`` decorator lets you create tasks without having any
  94. concrete app instance:
  95. :file:`demoapp/tasks.py`:
  96. .. literalinclude:: ../../examples/django/demoapp/tasks.py
  97. .. seealso::
  98. You can find the full source code for the Django example project at:
  99. https://github.com/celery/celery/tree/master/examples/django/
  100. .. admonition:: Relative Imports
  101. You have to be consistent in how you import the task module.
  102. For example, if you have ``project.app`` in ``INSTALLED_APPS``, then you
  103. must also import the tasks ``from project.app`` or else the names
  104. of the tasks will end up being different.
  105. See :ref:`task-naming-relative-imports`
  106. Extensions
  107. ==========
  108. .. _django-celery-results:
  109. ``django-celery-results`` - Using the Django ORM/Cache as a result backend
  110. --------------------------------------------------------------------------
  111. The :pypi:`django-celery-results` extension provides result backends
  112. using either the Django ORM, or the Django Cache framework.
  113. To use this with your project you need to follow these steps:
  114. #. Install the :pypi:`django-celery-results` library:
  115. .. code-block:: console
  116. $ pip install django-celery-results
  117. #. Add ``django_celery_results`` to ``INSTALLED_APPS`` in your
  118. Django project's :file:`settings.py`::
  119. INSTALLED_APPS = (
  120. ...,
  121. 'django_celery_results',
  122. )
  123. Note that there is no dash in the module name, only underscores.
  124. #. Create the Celery database tables by performing a database migrations:
  125. .. code-block:: console
  126. $ python manage.py migrate django_celery_results
  127. #. Configure Celery to use the :pypi:`django-celery-results` backend.
  128. Assuming you are using Django's :file:`settings.py` to also configure
  129. Celery, add the following settings:
  130. .. code-block:: python
  131. CELERY_RESULT_BACKEND = 'django-db'
  132. For the cache backend you can use:
  133. .. code-block:: python
  134. CELERY_RESULT_BACKEND = 'django-cache'
  135. ``django-celery-beat`` - Database-backed Periodic Tasks with Admin interface.
  136. -----------------------------------------------------------------------------
  137. See :ref:`beat-custom-schedulers` for more information.
  138. Starting the worker process
  139. ===========================
  140. In a production environment you'll want to run the worker in the background
  141. as a daemon - see :ref:`daemonizing` - but for testing and
  142. development it is useful to be able to start a worker instance by using the
  143. :program:`celery worker` manage command, much as you'd use Django's
  144. :command:`manage.py runserver`:
  145. .. code-block:: console
  146. $ celery -A proj worker -l info
  147. For a complete listing of the command-line options available,
  148. use the help command:
  149. .. code-block:: console
  150. $ celery help
  151. Where to go from here
  152. =====================
  153. If you want to learn more you should continue to the
  154. :ref:`Next Steps <next-steps>` tutorial, and after that you
  155. can study the :ref:`User Guide <guide>`.