first-steps-with-django.rst 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. =========================
  2. First steps with Django
  3. =========================
  4. Configuring your Django project to use Celery
  5. =============================================
  6. You need four simple steps to use celery with your Django project.
  7. 1. Install the ``django-celery`` library:
  8. .. code-block:: bash
  9. $ pip install django-celery
  10. 2. Add the following lines to ``settings.py``:
  11. .. code-block:: python
  12. import djcelery
  13. djcelery.setup_loader()
  14. 3. Add ``djcelery`` to ``INSTALLED_APPS``.
  15. 4. Create the celery database tables.
  16. If you are using south_ for schema migrations, you'll want to:
  17. .. code-block:: bash
  18. $ python manage.py migrate djcelery
  19. For those who are not using south, a normal ``syncdb`` will work:
  20. .. code-block:: bash
  21. $ python manage.py syncdb
  22. .. _south: http://pypi.python.org/pypi/South/
  23. By default Celery uses `RabbitMQ`_ as the broker, but there are several
  24. alternatives to choose from, see :ref:`celerytut-broker`.
  25. All settings mentioned in the Celery documentation should be added
  26. to your Django project's ``settings.py`` module. For example
  27. you can configure the :setting:`BROKER_URL` setting to specify
  28. what broker to use::
  29. BROKER_URL = 'amqp://guest:guest@localhost:5672/'
  30. That's it.
  31. .. _`RabbitMQ`: http://www.rabbitmq.com/
  32. Special note for mod_wsgi users
  33. -------------------------------
  34. If you're using ``mod_wsgi`` to deploy your Django application you need to
  35. include the following in your ``.wsgi`` module::
  36. import djcelery
  37. djcelery.setup_loader()
  38. Defining and calling tasks
  39. ==========================
  40. Tasks are defined by wrapping functions in the ``@task`` decorator.
  41. It is a common practice to put these in their own module named ``tasks.py``,
  42. and the worker will automatically go through the apps in ``INSTALLED_APPS``
  43. to import these modules.
  44. For a simple demonstration create a new Django app called
  45. ``celerytest``. To create this app you need to be in the directory
  46. of your Django project where ``manage.py`` is located and execute:
  47. .. code-block:: bash
  48. $ python manage.py startapp celerytest
  49. After the new app has been created, define a task by creating
  50. a new file called ``celerytest/tasks.py``:
  51. .. code-block:: python
  52. from celery import task
  53. @task()
  54. def add(x, y):
  55. return x + y
  56. Our example task is pretty pointless, it just returns the sum of two
  57. arguments, but it will do for demonstration, and it is referred to in many
  58. parts of the Celery documentation.
  59. .. admonition:: Relative Imports
  60. You have to consistent in how you import the task module, e.g. if
  61. you have ``project.app`` in ``INSTALLED_APPS`` then you also
  62. need to import the tasks ``from project.app`` or else the names
  63. of the tasks will be different.
  64. See :ref:`task-naming-relative-imports`
  65. Starting the worker process
  66. ===========================
  67. In a production environment you will want to run the worker in the background
  68. as a daemon - see :ref:`daemonizing` - but for testing and
  69. development it is useful to be able to start a worker instance by using the
  70. ``celery worker`` manage command, much as you would use Django's runserver:
  71. .. code-block:: bash
  72. $ python manage.py celery worker --loglevel=info
  73. For a complete listing of the command line options available,
  74. use the help command:
  75. .. code-block:: bash
  76. $ python manage.py celery help
  77. Calling our task
  78. ================
  79. Now that the worker is running, open up a new python interactive shell
  80. with ``python manage.py shell`` to actually call the task you defined::
  81. >>> from celerytest.tasks import add
  82. >>> add.delay(2, 2)
  83. Note that if you open a regular python shell by simply running ``python``
  84. you will need to import your Django application's settings by running::
  85. # Replace 'myproject' with your project's name
  86. >>> from myproject import settings
  87. The ``delay`` method used above is a handy shortcut to the ``apply_async``
  88. method which enables you to have greater control of the task execution.
  89. To read more about calling tasks, including specifying the time at which
  90. the task should be processed see :ref:`guide-calling`.
  91. .. note::
  92. Tasks need to be stored in a real module, they can't
  93. be defined in the python shell or IPython/bpython. This is because the
  94. worker server must be able to import the task function.
  95. The task should now be processed by the worker you started earlier,
  96. and you can verify that by looking at the worker's console output.
  97. Calling a task returns an :class:`~celery.result.AsyncResult` instance,
  98. which can be used to check the state of the task, wait for the task to finish
  99. or get its return value (or if the task failed, the exception and traceback).
  100. By default django-celery stores this state in the Django database.
  101. You may consider choosing an alternate result backend or disabling
  102. states alltogether (see :ref:`task-result-backends`).
  103. To demonstrate how the results work call the task again, but this time
  104. keep the result instance returned::
  105. >>> result = add.delay(4, 4)
  106. >>> result.ready() # returns True if the task has finished processing.
  107. False
  108. >>> result.result # task is not ready, so no return value yet.
  109. None
  110. >>> result.get() # Waits until the task is done and returns the retval.
  111. 8
  112. >>> result.result # direct access to result, doesn't re-raise errors.
  113. 8
  114. >>> result.successful() # returns True if the task didn't end in failure.
  115. True
  116. If the task raises an exception, the return value of ``result.successful()``
  117. will be ``False``, and ``result.result`` will contain the exception instance
  118. raised by the task.
  119. Where to go from here
  120. =====================
  121. To learn more you should read the `Celery User Guide`_, and the
  122. `Celery Documentation`_ in general.
  123. .. _`Celery User Guide`: http://docs.celeryproject.org/en/latest/userguide/
  124. .. _`Celery Documentation`: http://docs.celeryproject.org/