Skip to content
Myr

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

15 files+764 added−105 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)
modified:docs/patterns/packages.rst+2 added
65 unmodified lines
66To use the ``flask`` command and run your application you need to set67the ``--app`` option that tells Flask where to find the application68instance:6970.. code-block:: text7172 $ flask --app yourapplication run7374What did we gain from this? Now we can restructure the application a bit75into multiple modules. The only thing you have to remember is the
58 unmodified lines
modified:docs/index.rst+1 added
46 unmodified lines
47 logging48 config49 signals50 views51 lifecycle52 appcontext53 reqcontext54 blueprints55 extensions
32 unmodified lines
added:docs/lifecycle.rst+168 added
1Application Structure and Lifecycle2===================================34Flask makes it pretty easy to write a web application. But there are quite a few5different parts to an application and to each request it handles. Knowing what happens6during application setup, serving, and handling requests will help you know what's7possible in Flask and how to structure your application.8910Application Setup11-----------------1213The first step in creating a Flask application is creating the application object. Each14Flask application is an instance of the :class:`.Flask` class, which collects all15configuration, extensions, and views.1617.. code-block:: python1819 from flask import Flask2021 app = Flask(__name__)22 app.config.from_mapping(23 SECRET_KEY="dev",24 )25 app.config.from_prefixed_env()2627 @app.route("/")28 def index():29 return "Hello, World!"3031This is known as the "application setup phase", it's the code you write that's outside32any view functions or other handlers. It can be split up between different modules and33sub-packages, but all code that you want to be part of your application must be imported34in order for it to be registered.3536All application setup must be completed before you start serving your application and37handling requests. This is because WSGI servers divide work between multiple workers, or38can be distributed across multiple machines. If the configuration changed in one worker,39there's no way for Flask to ensure consistency between other workers.4041Flask tries to help developers catch some of these setup ordering issues by showing an42error if setup-related methods are called after requests are handled. In that case43you'll see this error:4445 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.4950However, it is not possible for Flask to detect all cases of out-of-order setup. In51general, don't do anything to modify the ``Flask`` app object and ``Blueprint`` objects52from within view functions that run during requests. This includes:5354- 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.626364Serving the Application65-----------------------6667Flask is a WSGI application framework. The other half of WSGI is the WSGI server. During68development, Flask, through Werkzeug, provides a development WSGI server with the69``flask run`` CLI command. When you are done with development, use a production server70to serve your application, see :doc:`deploying/index`.7172Regardless of what server you're using, it will follow the :pep:`3333` WSGI spec. The73WSGI server will be told how to access your Flask application object, which is the WSGI74application. Then it will start listening for HTTP requests, translate the request data75into a WSGI environ, and call the WSGI application with that data. The WSGI application76will return data that is translated into an HTTP response.7778#. 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.888990Middleware91~~~~~~~~~~9293The WSGI application above is a callable that behaves in a certain way. Middleware94is a WSGI application that wraps another WSGI application. It's a similar concept to95Python decorators. The outermost middleware will be called by the server. It can modify96the data passed to it, then call the WSGI application (or further middleware) that it97wraps, and so on. And it can take the return value of that call and modify it further.9899From the WSGI server's perspective, there is one WSGI application, the one it calls100directly. Typically, Flask is the "real" application at the end of the chain of101middleware. But even Flask can call further WSGI applications, although that's an102advanced, uncommon use case.103104A common middleware you'll see used with Flask is Werkzeug's105:class:`~werkzeug.middleware.proxy_fix.ProxyFix`, which modifies the request to look106like it came directly from a client even if it passed through HTTP proxies on the way.107There are other middleware that can handle serving static files, authentication, etc.108109110How a Request is Handled111------------------------112113For us, the interesting part of the steps above is when Flask gets called by the WSGI114server (or middleware). At that point, it will do quite a lot to handle the request and115generate the response. At the most basic, it will match the URL to a view function, call116the view function, and pass the return value back to the server. But there are many more117parts that you can use to customize its behavior.118119#. 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.164165There are even more decorators and customization points than this, but that aren't part166of every request lifecycle. They're more specific to certain things you might use during167a request, such as templates, building URLs, or handling JSON data. See the rest of this168documentation, as well as the :doc:`api` to explore further.
modified:docs/reqcontext.rst+3 added-2 removed
67 unmodified lines
68everything that runs in the block will have access to :data:`request`,69populated with your test data. ::7071 def generate_report(year):72 format = request.args.get('format')72 format = request.args.get("format")73 ...7475 with app.test_request_context(76 '/make_report/2017', data={'format': 'short'}):76 "/make_report/2017", query_string={"format": "short"}77 ):78 generate_report()7980If you see that error somewhere else in your code not related to81testing, it most likely indicates that you should move that code into a
167 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
1[project]2name = "flask-example-celery"3version = "1.0.0"4description = "Example Flask application with Celery background tasks."5readme = "README.md"6requires-python = ">=3.7"7dependencies = ["flask>=2.2.2", "celery[redis]>=5.2.7"]89[build-system]10requires = ["setuptools"]11build-backend = "setuptools.build_meta"
added:examples/celery/README.md+27 added
1Background Tasks with Celery2============================34This example shows how to configure Celery with Flask, how to set up an API for5submitting tasks and polling results, and how to use that API with JavaScript. See6[Flask's documentation about Celery](https://flask.palletsprojects.com/patterns/celery/).78From this directory, create a virtualenv and install the application into it. Then run a9Celery worker.1011```shell12$ python3 -m venv .venv13$ . ./.venv/bin/activate14$ pip install -r requirements.txt && pip install -e .15$ celery -A make_celery worker --loglevel INFO16```1718In a separate terminal, activate the virtualenv and run the Flask development server.1920```shell21$ . ./.venv/bin/activate22$ flask -A task_app --debug run23```2425Go to http://localhost:5000/ and use the forms to submit tasks. You can see the polling26requests in the browser dev tools and the Flask logs. You can see the tasks submitting27and 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#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
modified:src/flask/blueprints.py+38 added-32 removed
490 unmodified lines
491 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.497498 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 lines
517 @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`.523524 :param name: the optional name of the filter, otherwise the525 function name will be used.526 """
7 unmodified lines
534 @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`.541542 :param name: the optional name of the filter, otherwise the543 function name will be used.544 """
6 unmodified lines
551 @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`.557558 .. versionadded:: 0.10559560 :param name: the optional name of the test, otherwise the
9 unmodified lines
570 @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`.577578 .. versionadded:: 0.10579580 :param name: the optional name of the test, otherwise the
8 unmodified lines
589 @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`.595596 .. versionadded:: 0.10597598 :param name: the optional name of the global, otherwise the
9 unmodified lines
608 @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`.615616 .. versionadded:: 0.10617618 :param name: the optional name of the global, otherwise the
6 unmodified lines
625 self.record_once(register_template)626627 @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 lines
637 @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`.643644 .. deprecated:: 2.2645 Will be removed in Flask 2.3. Run setup code when creating646 the application instead.
11 unmodified lines
658 return f659660 @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 f669670 @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 lines
680 @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 lines
692 @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 """699700 def decorator(f: T_error_handler) -> T_error_handler:701 self.record_once(lambda s: s.app.errorhandler(code)(f))
4 unmodified lines
706 @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 f717718 @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 f
modified:src/flask/scaffold.py+39 added-1 removed
559 unmodified lines
560 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.564565 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 lines
581 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.585586 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 lines
615 execute code that might fail they must surround that code with a616 ``try``/``except`` block and log any errors.617618 The return values of teardown functions are ignored.619620 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 line
629 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.636637 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 f644645 @setupmethod
11 unmodified lines
657 every view.658659 The function is passed the endpoint name and values dict. The return660 value is ignored.661662 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 line
671 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.675676 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 lines
699 @app.errorhandler(DatabaseError)700 def special_exception_handler(error):701 return 'Database connection failed', 500702703 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`.707708 .. versionadded:: 0.7709 Use :meth:`register_error_handler` instead of modifying710 :attr:`error_handler_spec` directly, for application wide error711 handlers.
225 unmodified lines