celery.rst
This file
Path
docs/patterns/celery.rst
105 lines · 3.6 KiB
Last changed by
Merge branch '2.1.x'David Lordbefore adoption9e2e1de
History of this fileTake it
1Celery Background Tasks2=======================34If your application has a long running task, such as processing some uploaded5data or sending email, you don't want to wait for it to finish during a6request. Instead, use a task queue to send the necessary data to another7process that will run the task in the background while the request returns8immediately.910Celery is a powerful task queue that can be used for simple background tasks11as well as complex multi-stage programs and schedules. This guide will show you12how to configure Celery using Flask, but assumes you've already read the13`First Steps with Celery <https://celery.readthedocs.io/en/latest/getting-started/first-steps-with-celery.html>`_14guide in the Celery documentation.1516Install17-------1819Celery is a separate Python package. Install it from PyPI using pip::2021 $ pip install celery2223Configure24---------2526The first thing you need is a Celery instance, this is called the celery27application. It serves the same purpose as the :class:`~flask.Flask`28object in Flask, just for Celery. Since this instance is used as the29entry-point for everything you want to do in Celery, like creating tasks30and managing workers, it must be possible for other modules to import it.3132For instance you can place this in a ``tasks`` module. While you can use33Celery without any reconfiguration with Flask, it becomes a bit nicer by34subclassing tasks and adding support for Flask's application contexts and35hooking it up with the Flask configuration.3637This is all that is necessary to integrate Celery with Flask:3839.. code-block:: python4041 from celery import Celery4243 def make_celery(app):44 celery = Celery(app.import_name)45 celery.conf.update(app.config["CELERY_CONFIG"])4647 class ContextTask(celery.Task):48 def __call__(self, *args, **kwargs):49 with app.app_context():50 return self.run(*args, **kwargs)5152 celery.Task = ContextTask53 return celery5455The function creates a new Celery object, configures it with the broker56from the application config, updates the rest of the Celery config from57the Flask config and then creates a subclass of the task that wraps the58task execution in an application context.5960.. note::61 Celery 5.x deprecated uppercase configuration keys, and 6.x will62 remove them. See their official `migration guide`_.6364.. _migration guide: https://docs.celeryproject.org/en/stable/userguide/configuration.html#conf-old-settings-map.6566An example task67---------------6869Let's write a task that adds two numbers together and returns the result. We70configure Celery's broker and backend to use Redis, create a ``celery``71application using the factory from above, and then use it to define the task. ::7273 from flask import Flask7475 flask_app = Flask(__name__)76 flask_app.config.update(CELERY_CONFIG={77 'broker_url': 'redis://localhost:6379',78 'result_backend': 'redis://localhost:6379',79 })80 celery = make_celery(flask_app)8182 @celery.task()83 def add_together(a, b):84 return a + b8586This task can now be called in the background::8788 result = add_together.delay(23, 42)89 result.wait() # 659091Run a worker92------------9394If you jumped in and already executed the above code you will be95disappointed to learn that ``.wait()`` will never actually return.96That's because you also need to run a Celery worker to receive and execute the97task. ::9899 $ celery -A your_application.celery worker100101The ``your_application`` string has to point to your application's package102or module that creates the ``celery`` object.103104Now that the worker is running, ``wait`` will return the result once the task105is finished.