Skip to content
Myr

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 file

Take it

The walk stopped after 200 commits: lines older than 1035efc point at it.

Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc

lines 1–36why, one step back
1Celery Background Tasks
2=======================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.36

Merge branch '2.1.x'David Lordbefore adoption9e2e1de

line 37why, one step back
37This is all that is necessary to integrate Celery with Flask:

Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc

line 38why, one step back
38

Merge branch '2.1.x'David Lordbefore adoption9e2e1de

lines 39–40why, one step back
39.. code-block:: python
40

Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc

lines 41–43why, one step back
41 from celery import Celery
4243 def make_celery(app):

Merge branch '2.1.x'David Lordbefore adoption9e2e1de

lines 44–45why, one step back
44 celery = Celery(app.import_name)
45 celery.conf.update(app.config["CELERY_CONFIG"])

Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc

lines 46–59why, one step back
46
47 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.59

Merge branch '2.1.x'David Lordbefore adoption9e2e1de

lines 60–65why, one step back
60.. 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.65

Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc

lines 66–70why, one step back
66An example task
67---------------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``

Merge remote-tracking branch 'origin/2.0.x' into mainGrey Libefore adoptionba6db2e

line 71why, one step back
71application using the factory from above, and then use it to define the task. ::

Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc

lines 72–75why, one step back
72
73 from flask import Flask7475 flask_app = Flask(__name__)

Merge branch '2.1.x'David Lordbefore adoption9e2e1de

lines 76–79why, one step back
76 flask_app.config.update(CELERY_CONFIG={
77 'broker_url': 'redis://localhost:6379',78 'result_backend': 'redis://localhost:6379',79 })

Add command switch tabs for Bash, CMD and Powershell with sphinx-tabs (#3714)Grey Libefore adoption1035efc

lines 80–105why, one step back
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.