first-steps-with-django.rst 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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. Starting the worker process
  60. ===========================
  61. In a production environment you will want to run the worker in the background
  62. as a daemon - see :ref:`daemonizing` - but for testing and
  63. development it is useful to be able to start a worker instance by using the
  64. ``celery worker`` manage command, much as you would use Django's runserver:
  65. .. code-block:: bash
  66. $ python manage.py celery worker --loglevel=info
  67. For a complete listing of the command line options available,
  68. use the help command:
  69. .. code-block:: bash
  70. $ python manage.py celery help
  71. Calling our task
  72. ================
  73. Now that the worker is running, open up a new terminal to actually
  74. call the task you defined::
  75. >>> from celerytest.tasks import add
  76. >>> add.delay(2, 2)
  77. The ``delay`` method is a handy shortcut to the ``apply_async`` method which
  78. enables you to have greater control of the task execution.
  79. To read more about calling tasks, including specifying the time at which
  80. the task should be processed see :ref:`guide-calling`.
  81. .. note::
  82. Tasks need to be stored in a real module, they can't
  83. be defined in the python shell or IPython/bpython. This is because the
  84. worker server must be able to import the task function.
  85. The task should now be processed by the worker you started earlier,
  86. and you can verify that by looking at the worker's console output.
  87. Calling a task returns an :class:`~celery.result.AsyncResult` instance,
  88. which can be used to check the state of the task, wait for the task to finish
  89. or get its return value (or if the task failed, the exception and traceback).
  90. By default django-celery stores this state in the Django database.
  91. You may consider choosing an alternate result backend or disabling
  92. states alltogether (see :ref:`task-result-backends`).
  93. To demonstrate how the results work call the task again, but this time
  94. keep the result instance returned::
  95. >>> result = add.delay(4, 4)
  96. >>> result.ready() # returns True if the task has finished processing.
  97. False
  98. >>> result.result # task is not ready, so no return value yet.
  99. None
  100. >>> result.get() # Waits until the task is done and returns the retval.
  101. 8
  102. >>> result.result # direct access to result, doesn't re-raise errors.
  103. 8
  104. >>> result.successful() # returns True if the task didn't end in failure.
  105. True
  106. If the task raises an exception, the return value of ``result.successful()``
  107. will be ``False``, and ``result.result`` will contain the exception instance
  108. raised by the task.
  109. Where to go from here
  110. =====================
  111. To learn more you should read the `Celery User Guide`_, and the
  112. `Celery Documentation`_ in general.
  113. .. _`Celery User Guide`: http://docs.celeryproject.org/en/latest/userguide/
  114. .. _`Celery Documentation`: http://docs.celeryproject.org/