add celery example
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 dca8cf0 · Browse files · 9 files·+313 added−0 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+313 added−0 removed
- other:+313 added−0 removed
Provenance
- Commit
3f19524- Tree
ce85fe8- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
dca8cf0
9 files changed+313 added−0 removed
modified:docs/patterns/celery.rst+7 added
12 unmodified lines13 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 25 Install Celery from PyPI, for example using pip:186 unmodified lines212 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, Celery19 unmodified linesadded: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