Merge branch '2.2.x'
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 · parents 4ddb3f7, b945f98 · Browse files · 15 files·+764 added−105 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+764 added−105 removed
- other:+764 added−105 removed
Provenance
- Commit
a18ae3d- Tree
49a106a- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
4ddb3f7- Parent 2
b945f98
15 files changed+764 added−105 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)modified:docs/patterns/packages.rst+2 added
65 unmodified lines66 To use the ``flask`` command and run your application you need to set67 the ``--app`` option that tells Flask where to find the application68 instance:69 70+.. code-block:: text71+72 $ flask --app yourapplication run73 74 What did we gain from this? Now we can restructure the application a bit75 into multiple modules. The only thing you have to remember is the58 unmodified linesmodified:docs/index.rst+1 added
46 unmodified lines47 logging48 config49 signals50 views51+ lifecycle52 appcontext53 reqcontext54 blueprints55 extensions32 unmodified linesadded:docs/lifecycle.rst+168 added
1+Application Structure and Lifecycle2+===================================3+4+Flask makes it pretty easy to write a web application. But there are quite a few5+different parts to an application and to each request it handles. Knowing what happens6+during application setup, serving, and handling requests will help you know what's7+possible in Flask and how to structure your application.8+9+10+Application Setup11+-----------------12+13+The first step in creating a Flask application is creating the application object. Each14+Flask application is an instance of the :class:`.Flask` class, which collects all15+configuration, extensions, and views.16+17+.. code-block:: python18+19+ from flask import Flask20+21+ app = Flask(__name__)22+ app.config.from_mapping(23+ SECRET_KEY="dev",24+ )25+ app.config.from_prefixed_env()26+27+ @app.route("/")28+ def index():29+ return "Hello, World!"30+31+This is known as the "application setup phase", it's the code you write that's outside32+any view functions or other handlers. It can be split up between different modules and33+sub-packages, but all code that you want to be part of your application must be imported34+in order for it to be registered.35+36+All application setup must be completed before you start serving your application and37+handling requests. This is because WSGI servers divide work between multiple workers, or38+can be distributed across multiple machines. If the configuration changed in one worker,39+there's no way for Flask to ensure consistency between other workers.40+41+Flask tries to help developers catch some of these setup ordering issues by showing an42+error if setup-related methods are called after requests are handled. In that case43+you'll see this error:44+45+ The setup method 'route' can no longer be called on the application. It has already46+ handled its first request, any changes will not be applied consistently.47+ Make sure all imports, decorators, functions, etc. needed to set up the application48+ are done before running it.49+50+However, it is not possible for Flask to detect all cases of out-of-order setup. In51+general, don't do anything to modify the ``Flask`` app object and ``Blueprint`` objects52+from within view functions that run during requests. This includes:53+54+- Adding routes, view functions, and other request handlers with ``@app.route``,55+ ``@app.errorhandler``, ``@app.before_request``, etc.56+- Registering blueprints.57+- Loading configuration with ``app.config``.58+- Setting up the Jinja template environment with ``app.jinja_env``.59+- Setting a session interface, instead of the default itsdangerous cookie.60+- Setting a JSON provider with ``app.json``, instead of the default provider.61+- Creating and initializing Flask extensions.62+63+64+Serving the Application65+-----------------------66+67+Flask is a WSGI application framework. The other half of WSGI is the WSGI server. During68+development, Flask, through Werkzeug, provides a development WSGI server with the69+``flask run`` CLI command. When you are done with development, use a production server70+to serve your application, see :doc:`deploying/index`.71+72+Regardless of what server you're using, it will follow the :pep:`3333` WSGI spec. The73+WSGI server will be told how to access your Flask application object, which is the WSGI74+application. Then it will start listening for HTTP requests, translate the request data75+into a WSGI environ, and call the WSGI application with that data. The WSGI application76+will return data that is translated into an HTTP response.77+78+#. Browser or other client makes HTTP request.79+#. WSGI server receives request.80+#. WSGI server converts HTTP data to WSGI ``environ`` dict.81+#. WSGI server calls WSGI application with the ``environ``.82+#. Flask, the WSGI application, does all its internal processing to route the request83+ to a view function, handle errors, etc.84+#. Flask translates View function return into WSGI response data, passes it to WSGI85+ server.86+#. WSGI server creates and send an HTTP response.87+#. Client receives the HTTP response.88+89+90+Middleware91+~~~~~~~~~~92+93+The WSGI application above is a callable that behaves in a certain way. Middleware94+is a WSGI application that wraps another WSGI application. It's a similar concept to95+Python decorators. The outermost middleware will be called by the server. It can modify96+the data passed to it, then call the WSGI application (or further middleware) that it97+wraps, and so on. And it can take the return value of that call and modify it further.98+99+From the WSGI server's perspective, there is one WSGI application, the one it calls100+directly. Typically, Flask is the "real" application at the end of the chain of101+middleware. But even Flask can call further WSGI applications, although that's an102+advanced, uncommon use case.103+104+A common middleware you'll see used with Flask is Werkzeug's105+:class:`~werkzeug.middleware.proxy_fix.ProxyFix`, which modifies the request to look106+like it came directly from a client even if it passed through HTTP proxies on the way.107+There are other middleware that can handle serving static files, authentication, etc.108+109+110+How a Request is Handled111+------------------------112+113+For us, the interesting part of the steps above is when Flask gets called by the WSGI114+server (or middleware). At that point, it will do quite a lot to handle the request and115+generate the response. At the most basic, it will match the URL to a view function, call116+the view function, and pass the return value back to the server. But there are many more117+parts that you can use to customize its behavior.118+119+#. WSGI server calls the Flask object, which calls :meth:`.Flask.wsgi_app`.120+#. A :class:`.RequestContext` object is created. This converts the WSGI ``environ``121+ dict into a :class:`.Request` object. It also creates an :class:`AppContext` object.122+#. The :doc:`app context <appcontext>` is pushed, which makes :data:`.current_app` and123+ :data:`.g` available.124+#. The :data:`.appcontext_pushed` signal is sent.125+#. The :doc:`request context <reqcontext>` is pushed, which makes :attr:`.request` and126+ :class:`.session` available.127+#. The session is opened, loading any existing session data using the app's128+ :attr:`~.Flask.session_interface`, an instance of :class:`.SessionInterface`.129+#. The URL is matched against the URL rules registered with the :meth:`~.Flask.route`130+ decorator during application setup. If there is no match, the error - usually a 404,131+ 405, or redirect - is stored to be handled later.132+#. The :data:`.request_started` signal is sent.133+#. Any :meth:`~.Flask.url_value_preprocessor` decorated functions are called.134+#. Any :meth:`~.Flask.before_request` decorated functions are called. If any of135+ these function returns a value it is treated as the response immediately.136+#. If the URL didn't match a route a few steps ago, that error is raised now.137+#. The :meth:`~.Flask.route` decorated view function associated with the matched URL138+ is called and returns a value to be used as the response.139+#. If any step so far raised an exception, and there is an :meth:`~.Flask.errorhandler`140+ decorated function that matches the exception class or HTTP error code, it is141+ called to handle the error and return a response.142+#. Whatever returned a response value - a before request function, the view, or an143+ error handler, that value is converted to a :class:`.Response` object.144+#. Any :func:`~.after_this_request` decorated functions are called, then cleared.145+#. Any :meth:`~.Flask.after_request` decorated functions are called, which can modify146+ the response object.147+#. The session is saved, persisting any modified session data using the app's148+ :attr:`~.Flask.session_interface`.149+#. The :data:`.request_finished` signal is sent.150+#. If any step so far raised an exception, and it was not handled by an error handler151+ function, it is handled now. HTTP exceptions are treated as responses with their152+ corresponding status code, other exceptions are converted to a generic 500 response.153+ The :data:`.got_request_exception` signal is sent.154+#. The response object's status, headers, and body are returned to the WSGI server.155+#. Any :meth:`~.Flask.teardown_request` decorated functions are called.156+#. The :data:`.request_tearing_down` signal is sent.157+#. The request context is popped, :attr:`.request` and :class:`.session` are no longer158+ available.159+#. Any :meth:`~.Flask.teardown_appcontext` decorated functions are called.160+#. The :data:`.appcontext_tearing_down` signal is sent.161+#. The app context is popped, :data:`.current_app` and :data:`.g` are no longer162+ available.163+#. The :data:`.appcontext_popped` signal is sent.164+165+There are even more decorators and customization points than this, but that aren't part166+of every request lifecycle. They're more specific to certain things you might use during167+a request, such as templates, building URLs, or handling JSON data. See the rest of this168+documentation, as well as the :doc:`api` to explore further.modified:docs/reqcontext.rst+3 added-2 removed
67 unmodified lines68 everything that runs in the block will have access to :data:`request`,69 populated with your test data. ::70 71 def generate_report(year):72- format = request.args.get('format')72+ format = request.args.get("format")73 ...74 75 with app.test_request_context(76- '/make_report/2017', data={'format': 'short'}):76+ "/make_report/2017", query_string={"format": "short"}77+ ):78 generate_report()79 80 If you see that error somewhere else in your code not related to81 testing, it most likely indicates that you should move that code into a167 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
1+[project]2+name = "flask-example-celery"3+version = "1.0.0"4+description = "Example Flask application with Celery background tasks."5+readme = "README.md"6+requires-python = ">=3.7"7+dependencies = ["flask>=2.2.2", "celery[redis]>=5.2.7"]8+9+[build-system]10+requires = ["setuptools"]11+build-backend = "setuptools.build_meta"added:examples/celery/README.md+27 added
1+Background Tasks with Celery2+============================3+4+This example shows how to configure Celery with Flask, how to set up an API for5+submitting tasks and polling results, and how to use that API with JavaScript. See6+[Flask's documentation about Celery](https://flask.palletsprojects.com/patterns/celery/).7+8+From this directory, create a virtualenv and install the application into it. Then run a9+Celery worker.10+11+```shell12+$ python3 -m venv .venv13+$ . ./.venv/bin/activate14+$ pip install -r requirements.txt && pip install -e .15+$ celery -A make_celery worker --loglevel INFO16+```17+18+In a separate terminal, activate the virtualenv and run the Flask development server.19+20+```shell21+$ . ./.venv/bin/activate22+$ flask -A task_app --debug run23+```24+25+Go to http://localhost:5000/ and use the forms to submit tasks. You can see the polling26+requests in the browser dev tools and the Flask logs. You can see the tasks submitting27+and 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 flaskmodified:src/flask/blueprints.py+38 added-32 removed
490 unmodified lines491 view_func: t.Optional[ft.RouteCallable] = None,492 provide_automatic_options: t.Optional[bool] = None,493 **options: t.Any,494 ) -> None:495- """Like :meth:`Flask.add_url_rule` but for a blueprint. The endpoint for496- the :func:`url_for` function is prefixed with the name of the blueprint.495+ """Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for496+ full documentation.497+498+ The URL rule is prefixed with the blueprint's URL prefix. The endpoint name,499+ used with :func:`url_for`, is prefixed with the blueprint's name.500 """501 if endpoint and "." in endpoint:502 raise ValueError("'endpoint' may not contain a dot '.' character.")503 13 unmodified lines517 @setupmethod518 def app_template_filter(519 self, name: t.Optional[str] = None520 ) -> t.Callable[[T_template_filter], T_template_filter]:518- """Register a custom template filter, available application wide. Like519- :meth:`Flask.template_filter` but for a blueprint.521+ """Register a template filter, available in any template rendered by the522+ application. Equivalent to :meth:`.Flask.template_filter`.523 524 :param name: the optional name of the filter, otherwise the525 function name will be used.526 """7 unmodified lines534 @setupmethod535 def add_app_template_filter(536 self, f: ft.TemplateFilterCallable, name: t.Optional[str] = None537 ) -> None:535- """Register a custom template filter, available application wide. Like536- :meth:`Flask.add_template_filter` but for a blueprint. Works exactly537- like the :meth:`app_template_filter` decorator.538+ """Register a template filter, available in any template rendered by the539+ application. Works like the :meth:`app_template_filter` decorator. Equivalent to540+ :meth:`.Flask.add_template_filter`.541 542 :param name: the optional name of the filter, otherwise the543 function name will be used.544 """6 unmodified lines551 @setupmethod552 def app_template_test(553 self, name: t.Optional[str] = None554 ) -> t.Callable[[T_template_test], T_template_test]:552- """Register a custom template test, available application wide. Like553- :meth:`Flask.template_test` but for a blueprint.555+ """Register a template test, available in any template rendered by the556+ application. Equivalent to :meth:`.Flask.template_test`.557 558 .. versionadded:: 0.10559 560 :param name: the optional name of the test, otherwise the9 unmodified lines570 @setupmethod571 def add_app_template_test(572 self, f: ft.TemplateTestCallable, name: t.Optional[str] = None573 ) -> None:571- """Register a custom template test, available application wide. Like572- :meth:`Flask.add_template_test` but for a blueprint. Works exactly573- like the :meth:`app_template_test` decorator.574+ """Register a template test, available in any template rendered by the575+ application. Works like the :meth:`app_template_test` decorator. Equivalent to576+ :meth:`.Flask.add_template_test`.577 578 .. versionadded:: 0.10579 580 :param name: the optional name of the test, otherwise the8 unmodified lines589 @setupmethod590 def app_template_global(591 self, name: t.Optional[str] = None592 ) -> t.Callable[[T_template_global], T_template_global]:590- """Register a custom template global, available application wide. Like591- :meth:`Flask.template_global` but for a blueprint.593+ """Register a template global, available in any template rendered by the594+ application. Equivalent to :meth:`.Flask.template_global`.595 596 .. versionadded:: 0.10597 598 :param name: the optional name of the global, otherwise the9 unmodified lines608 @setupmethod609 def add_app_template_global(610 self, f: ft.TemplateGlobalCallable, name: t.Optional[str] = None611 ) -> None:609- """Register a custom template global, available application wide. Like610- :meth:`Flask.add_template_global` but for a blueprint. Works exactly611- like the :meth:`app_template_global` decorator.612+ """Register a template global, available in any template rendered by the613+ application. Works like the :meth:`app_template_global` decorator. Equivalent to614+ :meth:`.Flask.add_template_global`.615 616 .. versionadded:: 0.10617 618 :param name: the optional name of the global, otherwise the6 unmodified lines625 self.record_once(register_template)626 627 @setupmethod628 def before_app_request(self, f: T_before_request) -> T_before_request:626- """Like :meth:`Flask.before_request`. Such a function is executed627- before each request, even if outside of a blueprint.629+ """Like :meth:`before_request`, but before every request, not only those handled630+ by the blueprint. Equivalent to :meth:`.Flask.before_request`.631 """632 self.record_once(633 lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)634 )2 unmodified lines637 @setupmethod638 def before_app_first_request(639 self, f: T_before_first_request640 ) -> T_before_first_request:638- """Like :meth:`Flask.before_first_request`. Such a function is639- executed before the first request to the application.641+ """Register a function to run before the first request to the application is642+ handled by the worker. Equivalent to :meth:`.Flask.before_first_request`.643 644 .. deprecated:: 2.2645 Will be removed in Flask 2.3. Run setup code when creating646 the application instead.11 unmodified lines658 return f659 660 @setupmethod661 def after_app_request(self, f: T_after_request) -> T_after_request:659- """Like :meth:`Flask.after_request` but for a blueprint. Such a function660- is executed after each request, even if outside of the blueprint.662+ """Like :meth:`after_request`, but after every request, not only those handled663+ by the blueprint. Equivalent to :meth:`.Flask.after_request`.664 """665 self.record_once(666 lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)667 )668 return f669 670 @setupmethod671 def teardown_app_request(self, f: T_teardown) -> T_teardown:669- """Like :meth:`Flask.teardown_request` but for a blueprint. Such a670- function is executed when tearing down each request, even if outside of671- the blueprint.672+ """Like :meth:`teardown_request`, but after every request, not only those673+ handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`.674 """675 self.record_once(676 lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)677 )2 unmodified lines680 @setupmethod681 def app_context_processor(682 self, f: T_template_context_processor683 ) -> T_template_context_processor:682- """Like :meth:`Flask.context_processor` but for a blueprint. Such a683- function is executed each request, even if outside of the blueprint.684+ """Like :meth:`context_processor`, but for templates rendered by every view, not685+ only by the blueprint. Equivalent to :meth:`.Flask.context_processor`.686 """687 self.record_once(688 lambda s: s.app.template_context_processors.setdefault(None, []).append(f)689 )2 unmodified lines692 @setupmethod693 def app_errorhandler(694 self, code: t.Union[t.Type[Exception], int]695 ) -> t.Callable[[T_error_handler], T_error_handler]:694- """Like :meth:`Flask.errorhandler` but for a blueprint. This695- handler is used for all requests, even if outside of the blueprint.696+ """Like :meth:`errorhandler`, but for every request, not only those handled by697+ the blueprint. Equivalent to :meth:`.Flask.errorhandler`.698 """699 700 def decorator(f: T_error_handler) -> T_error_handler:701 self.record_once(lambda s: s.app.errorhandler(code)(f))4 unmodified lines706 @setupmethod707 def app_url_value_preprocessor(708 self, f: T_url_value_preprocessor709 ) -> T_url_value_preprocessor:708- """Same as :meth:`url_value_preprocessor` but application wide."""710+ """Like :meth:`url_value_preprocessor`, but for every request, not only those711+ handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`.712+ """713 self.record_once(714 lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)715 )716 return f717 718 @setupmethod719 def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults:716- """Same as :meth:`url_defaults` but application wide."""720+ """Like :meth:`url_defaults`, but for every request, not only those handled by721+ the blueprint. Equivalent to :meth:`.Flask.url_defaults`.722+ """723 self.record_once(724 lambda s: s.app.url_default_functions.setdefault(None, []).append(f)725 )726 return fmodified:src/flask/scaffold.py+39 added-1 removed
559 unmodified lines560 The function will be called without any arguments. If it returns561 a non-``None`` value, the value is handled as if it was the562 return value from the view, and further request handling is563 stopped.564+565+ This is available on both app and blueprint objects. When used on an app, this566+ executes before every request. When used on a blueprint, this executes before567+ every request that the blueprint handles. To register with a blueprint and568+ execute before every request, use :meth:`.Blueprint.before_app_request`.569 """570 self.before_request_funcs.setdefault(None, []).append(f)571 return f572 8 unmodified lines581 If a function raises an exception, any remaining582 ``after_request`` functions will not be called. Therefore, this583 should not be used for actions that must execute, such as to584 close resources. Use :meth:`teardown_request` for that.585+586+ This is available on both app and blueprint objects. When used on an app, this587+ executes after every request. When used on a blueprint, this executes after588+ every request that the blueprint handles. To register with a blueprint and589+ execute after every request, use :meth:`.Blueprint.after_app_request`.590 """591 self.after_request_funcs.setdefault(None, []).append(f)592 return f593 21 unmodified lines615 execute code that might fail they must surround that code with a616 ``try``/``except`` block and log any errors.617 618 The return values of teardown functions are ignored.619+620+ This is available on both app and blueprint objects. When used on an app, this621+ executes after every request. When used on a blueprint, this executes after622+ every request that the blueprint handles. To register with a blueprint and623+ execute after every request, use :meth:`.Blueprint.teardown_app_request`.624 """625 self.teardown_request_funcs.setdefault(None, []).append(f)626 return f627 1 unmodified line629 def context_processor(630 self,631 f: T_template_context_processor,632 ) -> T_template_context_processor:618- """Registers a template context processor function."""633+ """Registers a template context processor function. These functions run before634+ rendering a template. The keys of the returned dict are added as variables635+ available in the template.636+637+ This is available on both app and blueprint objects. When used on an app, this638+ is called for every rendered template. When used on a blueprint, this is called639+ for templates rendered from the blueprint's views. To register with a blueprint640+ and affect every template, use :meth:`.Blueprint.app_context_processor`.641+ """642 self.template_context_processors[None].append(f)643 return f644 645 @setupmethod11 unmodified lines657 every view.658 659 The function is passed the endpoint name and values dict. The return660 value is ignored.661+662+ This is available on both app and blueprint objects. When used on an app, this663+ is called for every request. When used on a blueprint, this is called for664+ requests that the blueprint handles. To register with a blueprint and affect665+ every request, use :meth:`.Blueprint.app_url_value_preprocessor`.666 """667 self.url_value_preprocessors[None].append(f)668 return f669 1 unmodified line671 def url_defaults(self, f: T_url_defaults) -> T_url_defaults:672 """Callback function for URL defaults for all view functions of the673 application. It's called with the endpoint and values and should674 update the values passed in place.675+676+ This is available on both app and blueprint objects. When used on an app, this677+ is called for every request. When used on a blueprint, this is called for678+ requests that the blueprint handles. To register with a blueprint and affect679+ every request, use :meth:`.Blueprint.app_url_defaults`.680 """681 self.url_default_functions[None].append(f)682 return f683 15 unmodified lines699 @app.errorhandler(DatabaseError)700 def special_exception_handler(error):701 return 'Database connection failed', 500702 703+ This is available on both app and blueprint objects. When used on an app, this704+ can handle errors from every request. When used on a blueprint, this can handle705+ errors from requests that the blueprint handles. To register with a blueprint706+ and affect every request, use :meth:`.Blueprint.app_errorhandler`.707+708 .. versionadded:: 0.7709 Use :meth:`register_error_handler` instead of modifying710 :attr:`error_handler_spec` directly, for application wide error711 handlers.225 unmodified lines