| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389 | .. _tut-celery:.. _first-steps:========================= First Steps with Celery=========================Celery is a task queue with batteries included.It is easy to use so that you can get started without learningthe full complexities of the problem it solves. It is designedaround best practices so that your product can scaleand integrate with other languages, and it comes with thetools and support you need to run such a system in production.In this tutorial you will learn the absolute basics of using Celery.You will learn about;- Choosing and installing a message broker.- Installing Celery and creating your first task- Starting the worker and calling tasks.- Keeping track of tasks as they transition through different states,  and inspecting return values.Celery may seem daunting at first - but don't worry - this tutorialwill get you started in no time. It is deliberately kept simple, soto not confuse you with advanced features.After you have finished this tutorialit's a good idea to browse the rest of the documentation,for example the :ref:`next-steps` tutorial, which willshowcase Celery's capabilities... contents::    :local:.. _celerytut-broker:Choosing a Broker=================Celery requires a solution to send and receive messages, usually thiscomes in the form of a separate service called a *message broker*.There are several choices available, including:RabbitMQ--------`RabbitMQ`_ is feature-complete, stable, durable and easy to install.It's an excellent choice for a production environment.Detailed information about using RabbitMQ with Celery:    :ref:`broker-rabbitmq`.. _`RabbitMQ`: http://www.rabbitmq.com/If you are using Ubuntu or Debian install RabbitMQ by executing thiscommand:.. code-block:: bash    $ sudo apt-get install rabbitmq-serverWhen the command completes the broker is already running in the background,ready to move messages for you: ``Starting rabbitmq-server: SUCCESS``.And don't worry if you're not running Ubuntu or Debian, you can go to thiswebsite to find similarly simple installation instructions for otherplatforms, including Microsoft Windows:    http://www.rabbitmq.com/download.htmlRedis-----`Redis`_ is also feature-complete, but is more susceptible to data loss inthe event of abrupt termination or power failures. Detailed information about using Redis:    :ref:`broker-redis`.. _`Redis`: http://redis.io/Using a database----------------Using a database as a message queue is not recommended, but can be sufficientfor very small installations.  Your options include:* :ref:`broker-sqlalchemy`* :ref:`broker-django`If you're already using a Django database for example, using it as yourmessage broker can be convenient while developing even if you use a morerobust system in production.Other brokers-------------In addition to the above, there are other experimental transport implementationsto choose from, including :ref:`Amazon SQS <broker-sqs>`, :ref:`broker-mongodb`and :ref:`IronMQ <broker-ironmq>`.See :ref:`broker-overview` for a full list... _celerytut-installation:Installing Celery=================Celery is on the Python Package Index (PyPI), so it can be installedwith standard Python tools like ``pip`` or ``easy_install``:.. code-block:: bash    $ pip install celeryApplication===========The first thing you need is a Celery instance, this is called the celeryapplication or just app in short.  Since this instance is used asthe entry-point for everything you want to do in Celery, like creating tasks andmanaging workers, it must be possible for other modules to import it.In this tutorial you will keep everything contained in a single module,but for larger projects you want to createa :ref:`dedicated module <project-layout>`.Let's create the file :file:`tasks.py`:.. code-block:: python    from celery import Celery    celery = Celery('tasks', broker='amqp://guest@localhost//')    @celery.task    def add(x, y):        return x + yThe first argument to :class:`~celery.app.Celery` is the name of the current module,this is needed so that names can be automatically generated, the secondargument is the broker keyword argument which specifies the URL of themessage broker you want to use, using RabbitMQ here, which is already thedefault option.  See :ref:`celerytut-broker` above for more choices,e.g. for Redis you can use ``redis://localhost``, or MongoDB:``mongodb://localhost``.You defined a single task, called ``add``, which returns the sum of two numbers... _celerytut-running-the-worker:Running the celery worker server================================You now run the worker by executing our program with the ``worker``argument:.. code-block:: bash    $ celery -A tasks worker --loglevel=infoIn production you will want to run the worker in thebackground as a daemon.  To do this you need to use the tools providedby your platform, or something like `supervisord`_ (see :ref:`daemonizing`for more information).For a complete listing of the command-line options available, do:.. code-block:: bash    $  celery worker --helpThere also several other commands available, and help is also available:.. code-block:: bash    $ celery help.. _`supervisord`: http://supervisord.org.. _celerytut-calling:Calling the task================To call our task you can use the :meth:`~@Task.delay` method.This is a handy shortcut to the :meth:`~@Task.apply_async`method which gives greater control of the task execution (see:ref:`guide-calling`)::    >>> from tasks import add    >>> add.delay(4, 4)The task has now been processed by the worker you started earlier,and you can verify that by looking at the workers console output.Calling a task returns an :class:`~@AsyncResult` instance,which can be used to check the state of the task, wait for the task to finishor get its return value (or if the task failed, the exception and traceback).But this isn't enabled by default, and you have to configure Celery touse a result backend, which is detailed in the next section... _celerytut-keeping-results:Keeping Results===============If you want to keep track of the tasks' states, Celery needs to store or sendthe states somewhere.  There are severalbuilt-in result backends to choose from: `SQLAlchemy`_/`Django`_ ORM,`Memcached`_, `Redis`_, AMQP (`RabbitMQ`_), and `MongoDB`_ -- or you can define your own... _`Memcached`: http://memcached.org.. _`MongoDB`: http://www.mongodb.org.. _`SQLAlchemy`: http://www.sqlalchemy.org/.. _`Django`: http://djangoproject.comFor this example you will use the `amqp` result backend, which sends statesas messages.  The backend is specified via the ``backend`` argument to:class:`@Celery`, (or via the :setting:`CELERY_RESULT_BACKEND` setting ifyou choose to use a configuration module)::    celery = Celery('tasks', backend='amqp', broker='amqp://')or if you want to use Redis as the result backend, but still use RabbitMQ asthe message broker (a popular combination)::    celery = Celery('tasks', backend='redis://localhost', broker='amqp://')To read more about result backends please see :ref:`task-result-backends`.Now with the result backend configured, let's call the task again.This time you'll hold on to the :class:`~@AsyncResult` instance returnedwhen you call a task::    >>> result = add.delay(4, 4)The :meth:`~@AsyncResult.ready` method returns whether the taskhas finished processing or not::    >>> result.ready()    FalseYou can wait for the result to complete, but this is rarely usedsince it turns the asynchronous call into a synchronous one::    >>> result.get(timeout=1)    8In case the task raised an exception, :meth:`~@AsyncResult.get` willre-raise the exception, but you can override this by specifyingthe ``propagate`` argument::    >>> result.get(propagate=False)If the task raised an exception you can also gain access to theoriginal traceback::    >>> result.traceback    ...See :mod:`celery.result` for the complete result object reference... _celerytut-configuration:Configuration=============Celery, like a consumer appliance doesn't need much to be operated.It has an input and an output, where you must connect the input to a broker and maybethe output to a result backend if so wanted.  But if you look closely at the backthere's a lid revealing loads of sliders, dials and buttons: this is the configuration.The default configuration should be good enough for most uses, but there'smany things to tweak so Celery works just the way you want it to.Reading about the options available is a good idea to get familiar with whatcan be configured. You can read about the options in the:ref:`configuration` reference.The configuration can be set on the app directly or by using a dedicatedconfiguration module.As an example you can configure the default serializer used for serializingtask payloads by changing the :setting:`CELERY_TASK_SERIALIZER` setting:.. code-block:: python    celery.conf.CELERY_TASK_SERIALIZER = 'json'If you are configuring many settings at once you can use ``update``:.. code-block:: python    celery.conf.update(        CELERY_TASK_SERIALIZER='json',        CELERY_RESULT_SERIALIZER='json',        CELERY_TIMEZONE='Europe/Oslo',        CELERY_ENABLE_UTC=True,    )For larger projects using a dedicated configuration module is useful,in fact you are discouraged from hard codingperiodic task intervals and task routing options, as it is muchbetter to keep this in a centralized location, and especially for librariesit makes it possible for users to control how they want your tasks to behave,you can also imagine your SysAdmin making simple changes to the configurationin the event of system trouble.You can tell your Celery instance to use a configuration module,by calling the :meth:`~@Celery.config_from_object` method:.. code-block:: python    celery.config_from_object('celeryconfig')This module is often called "``celeryconfig``", but you can use anymodule name.A module named ``celeryconfig.py`` must then be available to load from thecurrent directory or on the Python path, it could look like this::file:`celeryconfig.py`:.. code-block:: python    BROKER_URL = 'amqp://'    CELERY_RESULT_BACKEND = 'amqp://'    CELERY_TASK_SERIALIZER = 'json'    CELERY_RESULT_SERIALIZER = 'json'    CELERY_TIMEZONE = 'Europe/Oslo'    CELERY_ENABLE_UTC = TrueTo verify that your configuration file works properly, and doesn'tcontain any syntax errors, you can try to import it:.. code-block:: bash    $ python -m celeryconfigFor a complete reference of configuration options, see :ref:`configuration`.To demonstrate the power of configuration files, this how you wouldroute a misbehaving task to a dedicated queue::file:`celeryconfig.py`:.. code-block:: python    CELERY_ROUTES = {        'tasks.add': 'low-priority',    }Or instead of routing it you could rate limit the taskinstead, so that only 10 tasks of this type can be processed in a minute(10/m)::file:`celeryconfig.py`:.. code-block:: python    CELERY_ANNOTATIONS = {        'tasks.add': {'rate_limit': '10/m'}    }If you are using RabbitMQ, Redis or MongoDB as thebroker then you can also direct the workers to set a new rate limitfor the task at runtime:.. code-block:: bash    $ celery control rate_limit tasks.add 10/m    worker.example.com: OK        new rate limit set successfullySee :ref:`guide-routing` to read more about task routing,and the :setting:`CELERY_ANNOTATIONS` setting for more about annotations,or :ref:`guide-monitoring` for more about remote control commands,and how to monitor what your workers are doing.Where to go from here=====================If you want to learn more you should continue to the:ref:`Next Steps <next-steps>` tutorial, and after that youcan study the :ref:`User Guide <guide>`.
 |