first-steps-with-django.rst 7.3 KB

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