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 fileTake it
The walk stopped after 200 commits: lines older than 93a7f08 point at it.
Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
lines 1–2why, one step back1Background Tasks with Celery2============================pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 3why, one step back3Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
lines 4–7why, one step back4If your application has a long running task, such as processing some uploaded data or5sending 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.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 8why, one step back8Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
lines 9–12why, one step back9`Celery`_ is a powerful task queue that can be used for simple background tasks as well10as 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.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 13why, one step back13Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
lines 14–21why, one step back14.. _Celery: https://celery.readthedocs.io15.. _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.2021pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 22–24why, one step back22Install23-------24Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
line 25why, one step back25Install Celery from PyPI, for example using pip:pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 26why, one step back26Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
lines 27–28why, one step back27.. code-block:: text28pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 29–31why, one step back29 $ pip install celery3031Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
lines 32–33why, one step back32Integrate Celery with Flask33---------------------------pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 34why, one step back34Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
lines 35–36why, one step back35You can use Celery without any integration with Flask, but it's convenient to configure36it through Flask's config, and to let tasks access the Flask application.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 37why, one step back37Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
lines 38–40why, one step back38Celery uses similar ideas to Flask, with a ``Celery`` app object that has configuration39and registers tasks. While creating a Flask app, use the following code to create and40configure a Celery app as well.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 41why, one step back41Merge branch '2.1.x'David Lordbefore adoption9e2e1de
lines 42–43why, one step back42.. code-block:: python43Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
line 44why, one step back44 from celery import Celery, Taskpin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 45why, one step back45Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
lines 46–48why, one step back46 def celery_init_app(app: Flask) -> Celery:47 class FlaskTask(Task):48 def __call__(self, *args: object, **kwargs: object) -> object:pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 49–51why, one step back49 with app.app_context():50 return self.run(*args, **kwargs)51Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
lines 52–56why, one step back52 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_apppin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 57why, one step back57Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
lines 58–62why, one step back58This creates and returns a ``Celery`` app object. Celery `configuration`_ is taken from59the ``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.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 63why, one step back63Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
line 64why, one step back64.. _configuration: https://celery.readthedocs.io/en/stable/userguide/configuration.htmlMerge branch '2.1.x'David Lordbefore adoption9e2e1de
line 65why, one step back65Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
lines 66–68why, one step back66Here's a basic ``example.py`` that configures Celery to use Redis for communication. We67enable 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 back69Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
line 70why, one step back70.. code-block:: pythonpin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 71–73why, one step back7172 from flask import Flask73Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
lines 74–82why, one step back74 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)pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 83why, one step back83Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
lines 84–158why, one step back84Point 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:pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 159–160why, one step back159 return a + b160Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
lines 161–163why, one step back161Earlier, we configured Celery to ignore task results by default. Since we want to know162the 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.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 164–165why, one step back164165Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
lines 166–167why, one step back166Calling Tasks167-------------pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 168why, one step back168Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
lines 169–171why, one step back169The 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.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 172why, one step back172Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
lines 173–174why, one step back173A Celery worker must be running to run the task. Starting a worker is shown in the174previous sections.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 175why, one step back175Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
line 176why, one step back176.. code-block:: pythonpin os and python version in rtd buildDavid Lordbefore adoption93a7f08
line 177why, one step back177Merge branch '2.2.x'David Lordbefore adoptiona18ae3d
lines 178–242why, one step back178 from flask import request179180 @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)