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

1Background Tasks with Celery2============================34If 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.89`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.1314.. _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.202122Install23-------2425Install Celery from PyPI, for example using pip:2627.. code-block:: text2829    $ pip install celery303132Integrate Celery with Flask33---------------------------3435You 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.3738Celery 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.4142.. code-block:: python4344    from celery import Celery, Task4546    def celery_init_app(app: Flask) -> Celery:47        class FlaskTask(Task):48            def __call__(self, *args: object, **kwargs: object) -> object:49                with app.app_context():50                    return self.run(*args, **kwargs)5152        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_app5758This 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.6364.. _configuration: https://celery.readthedocs.io/en/stable/userguide/configuration.html6566Here'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.6970.. code-block:: python7172    from flask import Flask7374    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)8384Point 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:159        return a + b160161Earlier, 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.164165166Calling Tasks167-------------168169The 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.172173A Celery worker must be running to run the task. Starting a worker is shown in the174previous sections.175176.. code-block:: python177178    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)