Skip to content
Myr

Merge pull request #4968 from pallets/docs-celery

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

rewrite celery docs, add example application

authored by David Lord · committed by GitHub · parents 761e02e, 3f19524 · Browse files · 9 files+513 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

9 files+513 added−70 removed

  • other:+513 added−70 removed

9 files+513 added−70 removed

modified:docs/patterns/celery.rst+207 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.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-------2419Celery is a separate Python package. Install it from PyPI using pip::25Install Celery from PyPI, for example using pip:2627.. code-block:: text2829 $ pip install celery3023Configure24---------3126The 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.32Integrate Celery with Flask33---------------------------3432For 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.35You 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.3737This is all that is necessary to integrate Celery with Flask:38Celery 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:: python4341 from celery import Celery44 from celery import Celery, Task4543 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):46 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.Task = ContextTask53 return celery52 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_app5755The 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.58This 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.6360.. note::61 Celery 5.x deprecated uppercase configuration keys, and 6.x will62 remove them. See their official `migration guide`_.64.. _configuration: https://celery.readthedocs.io/en/stable/userguide/configuration.html6564.. _migration guide: https://docs.celeryproject.org/en/stable/userguide/configuration.html#conf-old-settings-map.66Here'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.6966An example task67---------------70.. code-block:: python7169Let'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. ::7272 from flask import Flask7375 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)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)8382 @celery.task()83 def add_together(a, b):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:159 return a + b16086This task can now be called in the background::161Earlier, 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.16488 result = add_together.delay(23, 42)89 result.wait() # 6516591Run a worker92------------166Calling Tasks167-------------16894If 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. ::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.17299 $ celery -A your_application.celery worker173A Celery worker must be running to run the task. Starting a worker is shown in the174previous sections.175101The ``your_application`` string has to point to your application's package102or module that creates the ``celery`` object.176.. code-block:: python177104Now that the worker is running, ``wait`` will return the result once the task105is finished.178 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)
added:examples/celery/src/task_app/templates/index.html+108 added
1<!doctype html>2<html>3<head>4 <meta charset=UTF-8>5 <title>Celery Example</title>6</head>7<body>8<h2>Celery Example</h2>9Execute background tasks with Celery. Submits tasks and shows results using JavaScript.1011<hr>12<h4>Add</h4>13<p>Start a task to add two numbers, then poll for the result.14<form id=add method=post action="{{ url_for("tasks.add") }}">15 <label>A <input type=number name=a value=4></label><br>16 <label>B <input type=number name=b value=2></label><br>17 <input type=submit>18</form>19<p>Result: <span id=add-result></span></p>2021<hr>22<h4>Block</h4>23<p>Start a task that takes 5 seconds. However, the response will return immediately.24<form id=block method=post action="{{ url_for("tasks.block") }}">25 <input type=submit>26</form>27<p id=block-result></p>2829<hr>30<h4>Process</h4>31<p>Start a task that counts, waiting one second each time, showing progress.32<form id=process method=post action="{{ url_for("tasks.process") }}">33 <label>Total <input type=number name=total value="10"></label><br>34 <input type=submit>35</form>36<p id=process-result></p>3738<script>39 const taskForm = (formName, doPoll, report) => {40 document.forms[formName].addEventListener("submit", (event) => {41 event.preventDefault()42 fetch(event.target.action, {43 method: "POST",44 body: new FormData(event.target)45 })46 .then(response => response.json())47 .then(data => {48 report(null)4950 const poll = () => {51 fetch(`/tasks/result/${data["result_id"]}`)52 .then(response => response.json())53 .then(data => {54 report(data)5556 if (!data["ready"]) {57 setTimeout(poll, 500)58 } else if (!data["successful"]) {59 console.error(formName, data)60 }61 })62 }6364 if (doPoll) {65 poll()66 }67 })68 })69 }7071 taskForm("add", true, data => {72 const el = document.getElementById("add-result")7374 if (data === null) {75 el.innerText = "submitted"76 } else if (!data["ready"]) {77 el.innerText = "waiting"78 } else if (!data["successful"]) {79 el.innerText = "error, check console"80 } else {81 el.innerText = data["value"]82 }83 })8485 taskForm("block", false, data => {86 document.getElementById("block-result").innerText = (87 "request finished, check celery log to see task finish in 5 seconds"88 )89 })9091 taskForm("process", true, data => {92 const el = document.getElementById("process-result")9394 if (data === null) {95 el.innerText = "submitted"96 } else if (!data["ready"]) {97 el.innerText = `${data["value"]["current"]} / ${data["value"]["total"]}`98 } else if (!data["successful"]) {99 el.innerText = "error, check console"100 } else {101 el.innerText = "✅ done"102 }103 console.log(data)104 })105106</script>107</body>108</html>
added:examples/celery/src/task_app/__init__.py+39 added
1from celery import Celery2from celery import Task3from flask import Flask4from flask import render_template567def create_app() -> Flask:8 app = Flask(__name__)9 app.config.from_mapping(10 CELERY=dict(11 broker_url="redis://localhost",12 result_backend="redis://localhost",13 task_ignore_result=True,14 ),15 )16 app.config.from_prefixed_env()17 celery_init_app(app)1819 @app.route("/")20 def index() -> str:21 return render_template("index.html")2223 from . import views2425 app.register_blueprint(views.bp)26 return app272829def celery_init_app(app: Flask) -> Celery:30 class FlaskTask(Task):31 def __call__(self, *args: object, **kwargs: object) -> object:32 with app.app_context():33 return self.run(*args, **kwargs)3435 celery_app = Celery(app.name, task_cls=FlaskTask)36 celery_app.config_from_object(app.config["CELERY"])37 celery_app.set_default()38 app.extensions["celery"] = celery_app39 return celery_app
added:examples/celery/src/task_app/tasks.py+23 added
1import time23from celery import shared_task4from celery import Task567@shared_task(ignore_result=False)8def add(a: int, b: int) -> int:9 return a + b101112@shared_task()13def block() -> None:14 time.sleep(5)151617@shared_task(bind=True, ignore_result=False)18def process(self: Task, total: int) -> object:19 for i in range(total):20 self.update_state(state="PROGRESS", meta={"current": i + 1, "total": total})21 time.sleep(1)2223 return {"current": total, "total": total}
added:examples/celery/src/task_app/views.py+38 added
1from celery.result import AsyncResult2from flask import Blueprint3from flask import request45from . import tasks67bp = Blueprint("tasks", __name__, url_prefix="/tasks")8910@bp.get("/result/<id>")11def result(id: str) -> dict[str, object]:12 result = AsyncResult(id)13 ready = result.ready()14 return {15 "ready": ready,16 "successful": result.successful() if ready else None,17 "value": result.get() if ready else result.result,18 }192021@bp.post("/add")22def add() -> dict[str, object]:23 a = request.form.get("a", type=int)24 b = request.form.get("b", type=int)25 result = tasks.add.delay(a, b)26 return {"result_id": result.id}272829@bp.post("/block")30def block() -> dict[str, object]:31 result = tasks.block.delay()32 return {"result_id": result.id}333435@bp.post("/process")36def process() -> dict[str, object]:37 result = tasks.process.delay(total=request.form.get("total", type=int))38 return {"result_id": result.id}
added:examples/celery/make_celery.py+4 added
1from task_app import create_app23flask_app = create_app()4celery_app = flask_app.extensions["celery"]
added:examples/celery/pyproject.toml+11 added
added:examples/celery/README.md+27 added
added:examples/celery/requirements.txt+56 added
1#2# This file is autogenerated by pip-compile with Python 3.103# by the following command:4#5# pip-compile pyproject.toml6#7amqp==5.1.18 # via kombu9async-timeout==4.0.210 # via redis11billiard==3.6.4.012 # via celery13celery[redis]==5.2.714 # via flask-example-celery (pyproject.toml)15click==8.1.316 # via17 # celery18 # click-didyoumean19 # click-plugins20 # click-repl21 # flask22click-didyoumean==0.3.023 # via celery24click-plugins==1.1.125 # via celery26click-repl==0.2.027 # via celery28flask==2.2.229 # via flask-example-celery (pyproject.toml)30itsdangerous==2.1.231 # via flask32jinja2==3.1.233 # via flask34kombu==5.2.435 # via celery36markupsafe==2.1.237 # via38 # jinja239 # werkzeug40prompt-toolkit==3.0.3641 # via click-repl42pytz==2022.7.143 # via celery44redis==4.5.145 # via celery46six==1.16.047 # via click-repl48vine==5.0.049 # via50 # amqp51 # celery52 # kombu53wcwidth==0.2.654 # via prompt-toolkit55werkzeug==2.2.256 # via flask