first-steps-with-django.rst 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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 will use the same API as non-Django users so it's recommended that
  12. you 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. To use Celery with your Django project you must first define
  16. an instance of the Celery library (called an "app")
  17. If you have a modern Django project layout like::
  18. - proj/
  19. - proj/__init__.py
  20. - proj/settings.py
  21. - proj/urls.py
  22. - manage.py
  23. then the recommended way is to create a new `proj/proj/celery.py` module
  24. that defines the Celery instance:
  25. :file: `proj/proj/celery.py`
  26. .. code-block:: python
  27. from __future__ import absolute_import
  28. import os
  29. from celery import Celery
  30. from django.conf import settings
  31. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')
  32. app = Celery('proj')
  33. app.config_from_object('django.conf:settings')
  34. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
  35. @app.task(bind=True)
  36. def debug_task(self):
  37. print('Request: {0!r}'.format(self.request))
  38. Then you need to import this app in your :file:`proj/proj/__init__py`
  39. module. This ensures that the app is loaded when Django starts
  40. so that the ``@shared_task`` decorator (mentioned later) will use it:
  41. :file:`proj/proj/__init__.py`:
  42. .. code-block:: python
  43. from __future__ import absolute_import
  44. from .celery import app
  45. Note that this example project layout is suitable for larger projects,
  46. for simple projects you may use a single contained module that defines
  47. both the app and tasks, like in the :ref:`tut-firsteps` tutorial.
  48. Let's break down what happens in the first module,
  49. first we import absolute imports from the future, so that our
  50. ``celery.py`` module will not crash with the library:
  51. .. code-block:: python
  52. from __future__ import absolute_import
  53. Then we set the default :envvar:`DJANGO_SETTINGS_MODULE`
  54. for the :program:`celery` command-line program:
  55. .. code-block:: python
  56. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')
  57. You don't need this line, but it saves you from always passing in the
  58. settings module to the celery program. It must always come before
  59. creating the app instances, which is what we do next:
  60. .. code-block:: python
  61. app = Celery('proj')
  62. This is our instance of the library, you can have many instances
  63. but there's probably no reason for that when using Django.
  64. We also add the Django settings module as a configuration source
  65. for Celery. This means that you don't have to use multiple
  66. configuration files, and instead configure Celery directly
  67. from the Django settings.
  68. You can pass the object directly here, but using a string is better since
  69. then the worker doesn't have to serialize the object when using Windows
  70. or execv:
  71. .. code-block:: python
  72. app.config_from_object('django.conf:settings')
  73. Next, a common practice for reusable apps is to define all tasks
  74. in a separate ``tasks.py`` module, and Celery does have a way to
  75. autodiscover these modules:
  76. .. code-block:: python
  77. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
  78. With the line above Celery will automatically discover tasks in reusable
  79. apps if you follow the ``tasks.py`` convention::
  80. - app1/
  81. - app1/tasks.py
  82. - app1/models.py
  83. - app2/
  84. - app2/tasks.py
  85. - app2/models.py
  86. This way you do not have to manually add the individual modules
  87. to the :setting:`CELERY_IMPORTS` setting. The ``lambda`` so that the
  88. autodiscovery can happen only when needed, and so that importing your
  89. module will not evaluate the Django settings object.
  90. Finally, the ``debug_task`` example is a task that dumps
  91. its own request information. This is using the new ``bind=True`` task option
  92. introduced in Celery 3.1 to easily refer to the current task instance.
  93. Using the Django ORM/Cache as a result backend.
  94. -----------------------------------------------
  95. The ``django-celery`` library defines result backends that
  96. uses the Django ORM and Django Cache frameworks.
  97. To use this with your project you need to follow these four steps:
  98. 1. Install the ``django-celery`` library:
  99. .. code-block:: bash
  100. $ pip install django-celery
  101. 2. Add ``djcelery`` to ``INSTALLED_APPS``.
  102. 3. Create the celery database tables.
  103. This step will create the tables used to store results
  104. when using the database result backend and the tables used
  105. by the database periodic task scheduler. You can skip
  106. this step if you don't use these.
  107. If you are using south_ for schema migrations, you'll want to:
  108. .. code-block:: bash
  109. $ python manage.py migrate djcelery
  110. For those who are not using south, a normal ``syncdb`` will work:
  111. .. code-block:: bash
  112. $ python manage.py syncdb
  113. 4. Configure celery to use the django-celery backend.
  114. For the database backend you must use:
  115. .. code-block:: python
  116. app.conf.update(
  117. CELERY_RESULT_BACKEND='djcelery.backends.database:DatabaseBackend',
  118. )
  119. For the cache backend you can use:
  120. .. code-block:: python
  121. app.conf.update(
  122. CELERY_RESULT_BACKEND='djcelery.backends.cache:CacheBackend',
  123. )
  124. If you have connected Celery to your Django settings then you can
  125. add this directly into your settings module (without the
  126. ``app.conf.update`` part)
  127. .. _south: http://pypi.python.org/pypi/South/
  128. .. admonition:: Relative Imports
  129. You have to be consistent in how you import the task module, e.g. if
  130. you have ``project.app`` in ``INSTALLED_APPS`` then you also
  131. need to import the tasks ``from project.app`` or else the names
  132. of the tasks will be different.
  133. See :ref:`task-naming-relative-imports`
  134. Starting the worker process
  135. ===========================
  136. In a production environment you will want to run the worker in the background
  137. as a daemon - see :ref:`daemonizing` - but for testing and
  138. development it is useful to be able to start a worker instance by using the
  139. ``celery worker`` manage command, much as you would use Django's runserver:
  140. .. code-block:: bash
  141. $ celery -A proj worker -l info
  142. For a complete listing of the command-line options available,
  143. use the help command:
  144. .. code-block:: bash
  145. $ celery help
  146. Where to go from here
  147. =====================
  148. If you want to learn more you should continue to the
  149. :ref:`Next Steps <next-steps>` tutorial, and after that you
  150. can study the :ref:`User Guide <guide>`.