first-steps-with-django.rst 5.1 KB

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