Skip to content
Myr

celery.rst

This file

Path

docs/patterns/celery.rst

101 lines · 3.5 KiB

Last changed by

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

History of this file

Take it

The walk stopped after 200 commits: lines older than 2b517a1 point at it.

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

lines 1–66why, 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.3637This is all that is necessary to properly integrate Celery with Flask::3839 from celery import Celery4041 def make_celery(app):42 celery = Celery(43 app.import_name,44 backend=app.config['CELERY_RESULT_BACKEND'],45 broker=app.config['CELERY_BROKER_URL']46 )47 celery.conf.update(app.config)4849 class ContextTask(celery.Task):50 def __call__(self, *args, **kwargs):51 with app.app_context():52 return self.run(*args, **kwargs)5354 celery.Task = ContextTask55 return celery5657The function creates a new Celery object, configures it with the broker58from the application config, updates the rest of the Celery config from59the Flask config and then creates a subclass of the task that wraps the60task execution in an application context.6162An example task63---------------6465Let's write a task that adds two numbers together and returns the result. We66configure Celery's broker and backend to use Redis, create a ``celery``

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

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

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

lines 68–101why, one step back
68
69 from flask import Flask7071 flask_app = Flask(__name__)72 flask_app.config.update(73 CELERY_BROKER_URL='redis://localhost:6379',74 CELERY_RESULT_BACKEND='redis://localhost:6379'75 )76 celery = make_celery(flask_app)7778 @celery.task()79 def add_together(a, b):80 return a + b8182This task can now be called in the background::8384 result = add_together.delay(23, 42)85 result.wait() # 658687Run a worker88------------8990If you jumped in and already executed the above code you will be91disappointed to learn that ``.wait()`` will never actually return.92That's because you also need to run a Celery worker to receive and execute the93task. ::9495 $ celery -A your_application.celery worker9697The ``your_application`` string has to point to your application's package98or module that creates the ``celery`` object.99100Now that the worker is running, ``wait`` will return the result once the task101is finished.