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
Provenance
- Commit
d552726- Tree
31b1ac3- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
761e02e- Parent 2
3f19524
9 files changed+513 added−70 removed
modified:docs/patterns/celery.rst+207 added-70 removed
1-Celery Background Tasks2-=======================1+Background Tasks with Celery2+============================3 4-If your application has a long running task, such as processing some uploaded5-data or sending email, you don't want to wait for it to finish during a6-request. Instead, use a task queue to send the necessary data to another7-process that will run the task in the background while the request returns8-immediately.4+If your application has a long running task, such as processing some uploaded data or5+sending email, you don't want to wait for it to finish during a request. Instead, use a6+task queue to send the necessary data to another process that will run the task in the7+background while the request returns immediately.8 10-Celery is a powerful task queue that can be used for simple background tasks11-as well as complex multi-stage programs and schedules. This guide will show you12-how 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>`_14-guide in the Celery documentation.9+`Celery`_ is a powerful task queue that can be used for simple background tasks as well10+as complex multi-stage programs and schedules. This guide will show you how to configure11+Celery using Flask. Read Celery's `First Steps with Celery`_ guide to learn how to use12+Celery itself.13 14+.. _Celery: https://celery.readthedocs.io15+.. _First Steps with Celery: https://celery.readthedocs.io/en/latest/getting-started/first-steps-with-celery.html16+17+The Flask repository contains `an example <https://github.com/pallets/flask/tree/main/examples/celery>`_18+based on the information on this page, which also shows how to use JavaScript to submit19+tasks and poll for progress and results.20+21+22 Install23 -------24 19-Celery is a separate Python package. Install it from PyPI using pip::25+Install Celery from PyPI, for example using pip:26 27+.. code-block:: text28+29 $ pip install celery30 23-Configure24----------31 26-The first thing you need is a Celery instance, this is called the celery27-application. It serves the same purpose as the :class:`~flask.Flask`28-object in Flask, just for Celery. Since this instance is used as the29-entry-point for everything you want to do in Celery, like creating tasks30-and managing workers, it must be possible for other modules to import it.32+Integrate Celery with Flask33+---------------------------34 32-For instance you can place this in a ``tasks`` module. While you can use33-Celery without any reconfiguration with Flask, it becomes a bit nicer by34-subclassing tasks and adding support for Flask's application contexts and35-hooking it up with the Flask configuration.35+You can use Celery without any integration with Flask, but it's convenient to configure36+it through Flask's config, and to let tasks access the Flask application.37 37-This is all that is necessary to integrate Celery with Flask:38+Celery uses similar ideas to Flask, with a ``Celery`` app object that has configuration39+and registers tasks. While creating a Flask app, use the following code to create and40+configure a Celery app as well.41 42 .. code-block:: python43 41- from celery import Celery44+ from celery import Celery, Task45 43- def make_celery(app):44- celery = Celery(app.import_name)45- celery.conf.update(app.config["CELERY_CONFIG"])46-47- 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)51 52- 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_app57 55-The function creates a new Celery object, configures it with the broker56-from the application config, updates the rest of the Celery config from57-the Flask config and then creates a subclass of the task that wraps the58-task execution in an application context.58+This creates and returns a ``Celery`` app object. Celery `configuration`_ is taken from59+the ``CELERY`` key in the Flask configuration. The Celery app is set as the default, so60+that it is seen during each request. The ``Task`` subclass automatically runs task61+functions with a Flask app context active, so that services like your database62+connections are available.63 60-.. 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.html65 64-.. _migration guide: https://docs.celeryproject.org/en/stable/userguide/configuration.html#conf-old-settings-map.66+Here's a basic ``example.py`` that configures Celery to use Redis for communication. We67+enable a result backend, but ignore results by default. This allows us to store results68+only for tasks where we care about the result.69 66-An example task67----------------70+.. code-block:: python71 69-Let's write a task that adds two numbers together and returns the result. We70-configure Celery's broker and backend to use Redis, create a ``celery``71-application using the factory from above, and then use it to define the task. ::72-72 from flask import Flask73 75- 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)83 82- @celery.task()83- def add_together(a, b):84+Point the ``celery worker`` command at this and it will find the ``celery_app`` object.85+86+.. code-block:: text87+88+ $ celery -A example worker --loglevel INFO89+90+You can also run the ``celery beat`` command to run tasks on a schedule. See Celery's91+docs for more information about defining schedules.92+93+.. code-block:: text94+95+ $ celery -A example beat --loglevel INFO96+97+98+Application Factory99+-------------------100+101+When using the Flask application factory pattern, call the ``celery_init_app`` function102+inside the factory. It sets ``app.extensions["celery"]`` to the Celery app object, which103+can be used to get the Celery app from the Flask app returned by the factory.104+105+.. code-block:: python106+107+ 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 app119+120+To use ``celery`` commands, Celery needs an app object, but that's no longer directly121+available. Create a ``make_celery.py`` file that calls the Flask app factory and gets122+the Celery app from the returned Flask app.123+124+.. code-block:: python125+126+ from example import create_app127+128+ flask_app = create_app()129+ celery_app = flask_app.extensions["celery"]130+131+Point the ``celery`` command to this file.132+133+.. code-block:: text134+135+ $ celery -A make_celery worker --loglevel INFO136+ $ celery -A make_celery beat --loglevel INFO137+138+139+Defining Tasks140+--------------141+142+Using ``@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 also144+means that the decorated tasks are tied to the specific Flask and Celery app instances,145+which could be an issue during testing if you change configuration for a test.146+147+Instead, use Celery's ``@shared_task`` decorator. This creates task objects that will148+access whatever the "current app" is, which is a similar concept to Flask's blueprints149+and app context. This is why we called ``celery_app.set_default()`` above.150+151+Here's an example task that adds two numbers together and returns the result.152+153+.. code-block:: python154+155+ from celery import shared_task156+157+ @shared_task(ignore_result=False)158+ def add_together(a: int, b: int) -> int:159 return a + b160 86-This task can now be called in the background::161+Earlier, we configured Celery to ignore task results by default. Since we want to know162+the return value of this task, we set ``ignore_result=False``. On the other hand, a task163+that didn't need a result, such as sending an email, wouldn't set this.164 88- result = add_together.delay(23, 42)89- result.wait() # 65165 91-Run a worker92-------------166+Calling Tasks167+-------------168 94-If you jumped in and already executed the above code you will be95-disappointed to learn that ``.wait()`` will never actually return.96-That's because you also need to run a Celery worker to receive and execute the97-task. ::169+The decorated function becomes a task object with methods to call it in the background.170+The simplest way is to use the ``delay(*args, **kwargs)`` method. See Celery's docs for171+more methods.172 99- $ celery -A your_application.celery worker173+A Celery worker must be running to run the task. Starting a worker is shown in the174+previous sections.175 101-The ``your_application`` string has to point to your application's package102-or module that creates the ``celery`` object.176+.. code-block:: python177 104-Now that the worker is running, ``wait`` will return the result once the task105-is finished.178+ from flask import request179+180+ @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}186+187+The route doesn't get the task's result immediately. That would defeat the purpose by188+blocking the response. Instead, we return the running task's result id, which we can use189+later to get the result.190+191+192+Getting Results193+---------------194+195+To fetch the result of the task we started above, we'll add another route that takes the196+result id we returned before. We return whether the task is finished (ready), whether it197+finished successfully, and what the return value (or error) was if it is finished.198+199+.. code-block:: python200+201+ from celery.result import AsyncResult202+203+ @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+ }211+212+Now you can start the task using the first route, then poll for the result using the213+second route. This keeps the Flask request workers from being blocked waiting for tasks214+to finish.215+216+The Flask repository contains `an example <https://github.com/pallets/flask/tree/main/examples/celery>`_217+using JavaScript to submit tasks and poll for progress and results.218+219+220+Passing Data to Tasks221+---------------------222+223+The "add" task above took two integers as arguments. To pass arguments to tasks, Celery224+has to serialize them to a format that it can pass to other processes. Therefore,225+passing complex objects is not recommended. For example, it would be impossible to pass226+a SQLAlchemy model object, since that object is probably not serializable and is tied to227+the session that queried it.228+229+Pass the minimal amount of data necessary to fetch or recreate any complex data within230+the task. Consider a task that will run when the logged in user asks for an archive of231+their data. The Flask request knows the logged in user, and has the user object queried232+from the database. It got that by querying the database for a given id, so the task can233+do the same thing. Pass the user's id rather than the user object.234+235+.. code-block:: python236+237+ @shared_task238+ def generate_user_archive(user_id: str) -> None:239+ user = db.session.get(User, user_id)240+ ...241+242+ 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>9+Execute background tasks with Celery. Submits tasks and shows results using JavaScript.10+11+<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>20+21+<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>28+29+<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>37+38+<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)49+50+ const poll = () => {51+ fetch(`/tasks/result/${data["result_id"]}`)52+ .then(response => response.json())53+ .then(data => {54+ report(data)55+56+ if (!data["ready"]) {57+ setTimeout(poll, 500)58+ } else if (!data["successful"]) {59+ console.error(formName, data)60+ }61+ })62+ }63+64+ if (doPoll) {65+ poll()66+ }67+ })68+ })69+ }70+71+ taskForm("add", true, data => {72+ const el = document.getElementById("add-result")73+74+ 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+ })84+85+ 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+ })90+91+ taskForm("process", true, data => {92+ const el = document.getElementById("process-result")93+94+ 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+ })105+106+</script>107+</body>108+</html>added:examples/celery/src/task_app/__init__.py+39 added
1+from celery import Celery2+from celery import Task3+from flask import Flask4+from flask import render_template5+6+7+def 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)18+19+ @app.route("/")20+ def index() -> str:21+ return render_template("index.html")22+23+ from . import views24+25+ app.register_blueprint(views.bp)26+ return app27+28+29+def 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)34+35+ 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_appadded:examples/celery/src/task_app/tasks.py+23 added
1+import time2+3+from celery import shared_task4+from celery import Task5+6+7+@shared_task(ignore_result=False)8+def add(a: int, b: int) -> int:9+ return a + b10+11+12+@shared_task()13+def block() -> None:14+ time.sleep(5)15+16+17+@shared_task(bind=True, ignore_result=False)18+def 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)22+23+ return {"current": total, "total": total}added:examples/celery/src/task_app/views.py+38 added
1+from celery.result import AsyncResult2+from flask import Blueprint3+from flask import request4+5+from . import tasks6+7+bp = Blueprint("tasks", __name__, url_prefix="/tasks")8+9+10+@bp.get("/result/<id>")11+def 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+ }19+20+21+@bp.post("/add")22+def 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}27+28+29+@bp.post("/block")30+def block() -> dict[str, object]:31+ result = tasks.block.delay()32+ return {"result_id": result.id}33+34+35+@bp.post("/process")36+def 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
1+from task_app import create_app2+3+flask_app = create_app()4+celery_app = flask_app.extensions["celery"]added:examples/celery/pyproject.toml+11 added
1234567891011[project]name = "flask-example-celery"version = "1.0.0"description = "Example Flask application with Celery background tasks."readme = "README.md"requires-python = ">=3.7"dependencies = ["flask>=2.2.2", "celery[redis]>=5.2.7"]
[build-system]requires = ["setuptools"]build-backend = "setuptools.build_meta"added:examples/celery/README.md+27 added
123456789101112131415161718192021222324252627Background Tasks with Celery============================
This example shows how to configure Celery with Flask, how to set up an API forsubmitting tasks and polling results, and how to use that API with JavaScript. See[Flask's documentation about Celery](https://flask.palletsprojects.com/patterns/celery/).
From this directory, create a virtualenv and install the application into it. Then run aCelery worker.
```shell$ python3 -m venv .venv$ . ./.venv/bin/activate$ pip install -r requirements.txt && pip install -e .$ celery -A make_celery worker --loglevel INFO```
In a separate terminal, activate the virtualenv and run the Flask development server.
```shell$ . ./.venv/bin/activate$ flask -A task_app --debug run```
Go to http://localhost:5000/ and use the forms to submit tasks. You can see the pollingrequests in the browser dev tools and the Flask logs. You can see the tasks submittingand completing in the Celery logs.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+#7+amqp==5.1.18+ # via kombu9+async-timeout==4.0.210+ # via redis11+billiard==3.6.4.012+ # via celery13+celery[redis]==5.2.714+ # via flask-example-celery (pyproject.toml)15+click==8.1.316+ # via17+ # celery18+ # click-didyoumean19+ # click-plugins20+ # click-repl21+ # flask22+click-didyoumean==0.3.023+ # via celery24+click-plugins==1.1.125+ # via celery26+click-repl==0.2.027+ # via celery28+flask==2.2.229+ # via flask-example-celery (pyproject.toml)30+itsdangerous==2.1.231+ # via flask32+jinja2==3.1.233+ # via flask34+kombu==5.2.435+ # via celery36+markupsafe==2.1.237+ # via38+ # jinja239+ # werkzeug40+prompt-toolkit==3.0.3641+ # via click-repl42+pytz==2022.7.143+ # via celery44+redis==4.5.145+ # via celery46+six==1.16.047+ # via click-repl48+vine==5.0.049+ # via50+ # amqp51+ # celery52+ # kombu53+wcwidth==0.2.654+ # via prompt-toolkit55+werkzeug==2.2.256+ # via flask