Skip to content
Myr

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

9 files+313 added−0 removed

modified:docs/patterns/celery.rst+7 added
12 unmodified lines
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-------2425Install Celery from PyPI, for example using pip:
186 unmodified lines
212Now 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, Celery
19 unmodified lines
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