Skip to content
Myr

celery.rst

This file

Path

docs/patterns/celery.rst

242 lines · 8.5 KiB

Last changed by

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

History of this file

Take it

The walk stopped after 200 commits: lines older than 41aaaf7 point at it.

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

lines 1–2why, one step back
1Background Tasks with Celery
2============================

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

line 3why, one step back
3

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

lines 4–7why, one step back
4If your application has a long running task, such as processing some uploaded data or
5sending email, you don't want to wait for it to finish during a request. Instead, use a6task queue to send the necessary data to another process that will run the task in the7background while the request returns immediately.

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

line 8why, one step back
8

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

lines 9–12why, one step back
9`Celery`_ is a powerful task queue that can be used for simple background tasks as well
10as complex multi-stage programs and schedules. This guide will show you how to configure11Celery using Flask. Read Celery's `First Steps with Celery`_ guide to learn how to use12Celery itself.

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

line 13why, one step back
13

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

lines 14–21why, one step back
14.. _Celery: https://celery.readthedocs.io
15.. _First Steps with Celery: https://celery.readthedocs.io/en/latest/getting-started/first-steps-with-celery.html1617The Flask repository contains `an example <https://github.com/pallets/flask/tree/main/examples/celery>`_18based on the information on this page, which also shows how to use JavaScript to submit19tasks and poll for progress and results.2021

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

lines 22–24why, one step back
22Install
23-------24

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

line 25why, one step back
25Install Celery from PyPI, for example using pip:

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

line 26why, one step back
26

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

lines 27–28why, one step back
27.. code-block:: text
28

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

lines 29–31why, one step back
29 $ pip install celery
3031

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

lines 32–33why, one step back
32Integrate Celery with Flask
33---------------------------

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

line 34why, one step back
34

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

lines 35–36why, one step back
35You can use Celery without any integration with Flask, but it's convenient to configure
36it through Flask's config, and to let tasks access the Flask application.

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

line 37why, one step back
37

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

lines 38–40why, one step back
38Celery uses similar ideas to Flask, with a ``Celery`` app object that has configuration
39and registers tasks. While creating a Flask app, use the following code to create and40configure a Celery app as well.

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

line 41why, one step back
41

Merge branch '2.1.x'David Lordbefore adoption9e2e1de

lines 42–43why, one step back
42.. code-block:: python
43

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

line 44why, one step back
44 from celery import Celery, Task

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

line 45why, one step back
45

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

lines 46–48why, one step back
46 def celery_init_app(app: Flask) -> Celery:
47 class FlaskTask(Task):48 def __call__(self, *args: object, **kwargs: object) -> object:

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

lines 49–51why, one step back
49 with app.app_context():
50 return self.run(*args, **kwargs)51

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

lines 52–56why, one step back
52 celery_app = Celery(app.name, task_cls=FlaskTask)
53 celery_app.config_from_object(app.config["CELERY"])54 celery_app.set_default()55 app.extensions["celery"] = celery_app56 return celery_app

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

line 57why, one step back
57

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

lines 58–62why, one step back
58This creates and returns a ``Celery`` app object. Celery `configuration`_ is taken from
59the ``CELERY`` key in the Flask configuration. The Celery app is set as the default, so60that it is seen during each request. The ``Task`` subclass automatically runs task61functions with a Flask app context active, so that services like your database62connections are available.

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

line 63why, one step back
63

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

line 64why, one step back
64.. _configuration: https://celery.readthedocs.io/en/stable/userguide/configuration.html

Merge branch '2.1.x'David Lordbefore adoption9e2e1de

line 65why, one step back
65

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

lines 66–68why, one step back
66Here's a basic ``example.py`` that configures Celery to use Redis for communication. We
67enable a result backend, but ignore results by default. This allows us to store results68only for tasks where we care about the result.

Merge branch '2.1.x'David Lordbefore adoption9e2e1de

line 69why, one step back
69

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

line 70why, one step back
70.. code-block:: python

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

lines 71–73why, one step back
71
72 from flask import Flask73

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

lines 74–82why, one step back
74 app = Flask(__name__)
75 app.config.from_mapping(76 CELERY=dict(77 broker_url="redis://localhost",78 result_backend="redis://localhost",79 task_ignore_result=True,80 ),81 )82 celery_app = celery_init_app(app)

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

line 83why, one step back
83

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

lines 84–158why, one step back
84Point the ``celery worker`` command at this and it will find the ``celery_app`` object.
8586.. code-block:: text8788 $ celery -A example worker --loglevel INFO8990You can also run the ``celery beat`` command to run tasks on a schedule. See Celery's91docs for more information about defining schedules.9293.. code-block:: text9495 $ celery -A example beat --loglevel INFO969798Application Factory99-------------------100101When using the Flask application factory pattern, call the ``celery_init_app`` function102inside the factory. It sets ``app.extensions["celery"]`` to the Celery app object, which103can be used to get the Celery app from the Flask app returned by the factory.104105.. code-block:: python106107 def create_app() -> Flask:108 app = Flask(__name__)109 app.config.from_mapping(110 CELERY=dict(111 broker_url="redis://localhost",112 result_backend="redis://localhost",113 task_ignore_result=True,114 ),115 )116 app.config.from_prefixed_env()117 celery_init_app(app)118 return app119120To use ``celery`` commands, Celery needs an app object, but that's no longer directly121available. Create a ``make_celery.py`` file that calls the Flask app factory and gets122the Celery app from the returned Flask app.123124.. code-block:: python125126 from example import create_app127128 flask_app = create_app()129 celery_app = flask_app.extensions["celery"]130131Point the ``celery`` command to this file.132133.. code-block:: text134135 $ celery -A make_celery worker --loglevel INFO136 $ celery -A make_celery beat --loglevel INFO137138139Defining Tasks140--------------141142Using ``@celery_app.task`` to decorate task functions requires access to the143``celery_app`` object, which won't be available when using the factory pattern. It also144means that the decorated tasks are tied to the specific Flask and Celery app instances,145which could be an issue during testing if you change configuration for a test.146147Instead, use Celery's ``@shared_task`` decorator. This creates task objects that will148access whatever the "current app" is, which is a similar concept to Flask's blueprints149and app context. This is why we called ``celery_app.set_default()`` above.150151Here's an example task that adds two numbers together and returns the result.152153.. code-block:: python154155 from celery import shared_task156157 @shared_task(ignore_result=False)158 def add_together(a: int, b: int) -> int:

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

lines 159–160why, one step back
159 return a + b
160

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

lines 161–163why, one step back
161Earlier, we configured Celery to ignore task results by default. Since we want to know
162the return value of this task, we set ``ignore_result=False``. On the other hand, a task163that didn't need a result, such as sending an email, wouldn't set this.

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

lines 164–165why, one step back
164
165

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

lines 166–167why, one step back
166Calling Tasks
167-------------

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

line 168why, one step back
168

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

lines 169–171why, one step back
169The decorated function becomes a task object with methods to call it in the background.
170The simplest way is to use the ``delay(*args, **kwargs)`` method. See Celery's docs for171more methods.

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

line 172why, one step back
172

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

lines 173–174why, one step back
173A Celery worker must be running to run the task. Starting a worker is shown in the
174previous sections.

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

line 175why, one step back
175

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

line 176why, one step back
176.. code-block:: python

clean up unused function from prefixed_env prDavid Lordbefore adoption41aaaf7

line 177why, one step back
177

Merge branch '2.2.x'David Lordbefore adoptiona18ae3d

lines 178–242why, one step back
178 from flask import request
179180 @app.post("/add")181 def start_add() -> dict[str, object]:182 a = request.form.get("a", type=int)183 b = request.form.get("b", type=int)184 result = add_together.delay(a, b)185 return {"result_id": result.id}186187The route doesn't get the task's result immediately. That would defeat the purpose by188blocking the response. Instead, we return the running task's result id, which we can use189later to get the result.190191192Getting Results193---------------194195To fetch the result of the task we started above, we'll add another route that takes the196result id we returned before. We return whether the task is finished (ready), whether it197finished successfully, and what the return value (or error) was if it is finished.198199.. code-block:: python200201 from celery.result import AsyncResult202203 @app.get("/result/<id>")204 def task_result(id: str) -> dict[str, object]:205 result = AsyncResult(id)206 return {207 "ready": result.ready(),208 "successful": result.successful(),209 "value": result.result if result.ready() else None,210 }211212Now you can start the task using the first route, then poll for the result using the213second route. This keeps the Flask request workers from being blocked waiting for tasks214to finish.215216The Flask repository contains `an example <https://github.com/pallets/flask/tree/main/examples/celery>`_217using JavaScript to submit tasks and poll for progress and results.218219220Passing Data to Tasks221---------------------222223The "add" task above took two integers as arguments. To pass arguments to tasks, Celery224has to serialize them to a format that it can pass to other processes. Therefore,225passing complex objects is not recommended. For example, it would be impossible to pass226a SQLAlchemy model object, since that object is probably not serializable and is tied to227the session that queried it.228229Pass the minimal amount of data necessary to fetch or recreate any complex data within230the task. Consider a task that will run when the logged in user asks for an archive of231their data. The Flask request knows the logged in user, and has the user object queried232from the database. It got that by querying the database for a given id, so the task can233do the same thing. Pass the user's id rather than the user object.234235.. code-block:: python236237 @shared_task238 def generate_user_archive(user_id: str) -> None:239 user = db.session.get(User, user_id)240 ...241242 generate_user_archive.delay(current_user.id)