Skip to content
Myr

rewrite celery background tasks docs

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by David Lord · parent dd2423e · Browse files · 1 file+200 added−70 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+200 added−70 removed

  • other:+200 added−70 removed

1 file+200 added−70 removed

modified:docs/patterns/celery.rst+200 added-70 removed
1Celery Background Tasks2=======================1Background Tasks with Celery2============================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.4If 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.810Celery 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.9`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.html161718Install19-------2019Celery is a separate Python package. Install it from PyPI using pip::21Install Celery from PyPI, for example using pip:2223.. code-block:: text2425 $ pip install celery2623Configure24---------2726The 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.28Integrate Celery with Flask29---------------------------3032For 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.31You can use Celery without any integration with Flask, but it's convenient to configure32it through Flask's config, and to let tasks access the Flask application.3337This is all that is necessary to integrate Celery with Flask:34Celery uses similar ideas to Flask, with a ``Celery`` app object that has configuration35and registers tasks. While creating a Flask app, use the following code to create and36configure a Celery app as well.3738.. code-block:: python3941 from celery import Celery40 from celery import Celery, Task4143 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):42 def celery_init_app(app: Flask) -> Celery:43 class FlaskTask(Task):44 def __call__(self, *args: object, **kwargs: object) -> object:45 with app.app_context():46 return self.run(*args, **kwargs)4752 celery.Task = ContextTask53 return celery48 celery_app = Celery(app.name, task_cls=FlaskTask)49 celery_app.config_from_object(app.config["CELERY"])50 celery_app.set_default()51 app.extensions["celery"] = celery_app52 return celery_app5355The 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.54This creates and returns a ``Celery`` app object. Celery `configuration`_ is taken from55the ``CELERY`` key in the Flask configuration. The Celery app is set as the default, so56that it is seen during each request. The ``Task`` subclass automatically runs task57functions with a Flask app context active, so that services like your database58connections are available.5960.. note::61 Celery 5.x deprecated uppercase configuration keys, and 6.x will62 remove them. See their official `migration guide`_.60.. _configuration: https://celery.readthedocs.io/en/stable/userguide/configuration.html6164.. _migration guide: https://docs.celeryproject.org/en/stable/userguide/configuration.html#conf-old-settings-map.62Here's a basic ``example.py`` that configures Celery to use Redis for communication. We63enable a result backend, but ignore results by default. This allows us to store results64only for tasks where we care about the result.6566An example task67---------------66.. code-block:: python6769Let'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. ::7268 from flask import Flask6975 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)70 app = Flask(__name__)71 app.config.from_mapping(72 CELERY=dict(73 broker_url="redis://localhost",74 result_backend="redis://localhost",75 task_ignore_result=True,76 ),77 )78 celery_app = celery_init_app(app)7982 @celery.task()83 def add_together(a, b):80Point the ``celery worker`` command at this and it will find the ``celery_app`` object.8182.. code-block:: text8384 $ celery -A example worker --loglevel INFO8586You can also run the ``celery beat`` command to run tasks on a schedule. See Celery's87docs for more information about defining schedules.8889.. code-block:: text9091 $ celery -A example beat --loglevel INFO929394Application Factory95-------------------9697When using the Flask application factory pattern, call the ``celery_init_app`` function98inside the factory. It sets ``app.extensions["celery"]`` to the Celery app object, which99can be used to get the Celery app from the Flask app returned by the factory.100101.. code-block:: python102103 def create_app() -> Flask:104 app = Flask(__name__)105 app.config.from_mapping(106 CELERY=dict(107 broker_url="redis://localhost",108 result_backend="redis://localhost",109 task_ignore_result=True,110 ),111 )112 app.config.from_prefixed_env()113 celery_init_app(app)114 return app115116To use ``celery`` commands, Celery needs an app object, but that's no longer directly117available. Create a ``make_celery.py`` file that calls the Flask app factory and gets118the Celery app from the returned Flask app.119120.. code-block:: python121122 from example import create_app123124 flask_app = create_app()125 celery_app = flask_app.extensions["celery"]126127Point the ``celery`` command to this file.128129.. code-block:: text130131 $ celery -A make_celery worker --loglevel INFO132 $ celery -A make_celery beat --loglevel INFO133134135Defining Tasks136--------------137138Using ``@celery_app.task`` to decorate task functions requires access to the139``celery_app`` object, which won't be available when using the factory pattern. It also140means that the decorated tasks are tied to the specific Flask and Celery app instances,141which could be an issue during testing if you change configuration for a test.142143Instead, use Celery's ``@shared_task`` decorator. This creates task objects that will144access whatever the "current app" is, which is a similar concept to Flask's blueprints145and app context. This is why we called ``celery_app.set_default()`` above.146147Here's an example task that adds two numbers together and returns the result.148149.. code-block:: python150151 from celery import shared_task152153 @shared_task(ignore_result=False)154 def add_together(a: int, b: int) -> int:155 return a + b15686This task can now be called in the background::157Earlier, we configured Celery to ignore task results by default. Since we want to know158the return value of this task, we set ``ignore_result=False``. On the other hand, a task159that didn't need a result, such as sending an email, wouldn't set this.16088 result = add_together.delay(23, 42)89 result.wait() # 6516191Run a worker92------------162Calling Tasks163-------------16494If 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. ::165The decorated function becomes a task object with methods to call it in the background.166The simplest way is to use the ``delay(*args, **kwargs)`` method. See Celery's docs for167more methods.16899 $ celery -A your_application.celery worker169A Celery worker must be running to run the task. Starting a worker is shown in the170previous sections.171101The ``your_application`` string has to point to your application's package102or module that creates the ``celery`` object.172.. code-block:: python173104Now that the worker is running, ``wait`` will return the result once the task105is finished.174 from flask import request175176 @app.post("/add")177 def start_add() -> dict[str, object]:178 a = request.form.get("a", type=int)179 b = request.form.get("b", type=int)180 result = add_together.delay(a, b)181 return {"result_id": result.id}182183The route doesn't get the task's result immediately. That would defeat the purpose by184blocking the response. Instead, we return the running task's result id, which we can use185later to get the result.186187188Getting Results189---------------190191To fetch the result of the task we started above, we'll add another route that takes the192result id we returned before. We return whether the task is finished (ready), whether it193finished successfully, and what the return value (or error) was if it is finished.194195.. code-block:: python196197 from celery.result import AsyncResult198199 @app.get("/result/<id>")200 def task_result(id: str) -> dict[str, object]:201 result = AsyncResult(id)202 return {203 "ready": result.ready(),204 "successful": result.successful(),205 "value": result.result if result.ready() else None,206 }207208Now you can start the task using the first route, then poll for the result using the209second route. This keeps the Flask request workers from being blocked waiting for tasks210to finish.211212213Passing Data to Tasks214---------------------215216The "add" task above took two integers as arguments. To pass arguments to tasks, Celery217has to serialize them to a format that it can pass to other processes. Therefore,218passing complex objects is not recommended. For example, it would be impossible to pass219a SQLAlchemy model object, since that object is probably not serializable and is tied to220the session that queried it.221222Pass the minimal amount of data necessary to fetch or recreate any complex data within223the task. Consider a task that will run when the logged in user asks for an archive of224their data. The Flask request knows the logged in user, and has the user object queried225from the database. It got that by querying the database for a given id, so the task can226do the same thing. Pass the user's id rather than the user object.227228.. code-block:: python229230 @shared_task231 def generate_user_archive(user_id: str) -> None:232 user = db.session.get(User, user_id)233 ...234235 generate_user_archive.delay(current_user.id)