Skip to content
Myr

Merge pull request #3412 from pgjones/async

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Add `async` support

authored by David Lord · committed by GitHub · parents 9ddef01, dc3e9c0 · Browse files · 13 files+380 added−23 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

13 files+380 added−23 removed

  • tests:+139 added−0 removed
  • other:+241 added−23 removed

13 files+380 added−23 removed

added:docs/async-await.rst+81 added
1.. _async_await:23Using ``async`` and ``await``4=============================56.. versionadded:: 2.078Routes, error handlers, before request, after request, and teardown9functions can all be coroutine functions if Flask is installed with the10``async`` extra (``pip install flask[async]``). This allows views to be11defined with ``async def`` and use ``await``.1213.. code-block:: python1415 @app.route("/get-data")16 async def get_data():17 data = await async_db_query(...)18 return jsonify(data)192021Performance22-----------2324Async functions require an event loop to run. Flask, as a WSGI25application, uses one worker to handle one request/response cycle.26When a request comes in to an async view, Flask will start an event loop27in a thread, run the view function there, then return the result.2829Each request still ties up one worker, even for async views. The upside30is that you can run async code within a view, for example to make31multiple concurrent database queries, HTTP requests to an external API,32etc. However, the number of requests your application can handle at one33time will remain the same.3435**Async is not inherently faster than sync code.** Async is beneficial36when performing concurrent IO-bound tasks, but will probably not improve37CPU-bound tasks. Traditional Flask views will still be appropriate for38most use cases, but Flask's async support enables writing and using39code that wasn't possible natively before.404142When to use Quart instead43-------------------------4445Flask's async support is less performant than async-first frameworks due46to the way it is implemented. If you have a mainly async codebase it47would make sense to consider `Quart`_. Quart is a reimplementation of48Flask based on the `ASGI`_ standard instead of WSGI. This allows it to49handle many concurrent requests, long running requests, and websockets50without requiring individual worker processes or threads.5152It has also already been possible to run Flask with Gevent or Eventlet53to get many of the benefits of async request handling. These libraries54patch low-level Python functions to accomplish this, whereas ``async``/55``await`` and ASGI use standard, modern Python capabilities. Deciding56whether you should use Flask, Quart, or something else is ultimately up57to understanding the specific needs of your project.5859.. _Quart: https://gitlab.com/pgjones/quart60.. _ASGI: https://asgi.readthedocs.io/en/latest/616263Extensions64----------6566Existing Flask extensions only expect views to be synchronous. If they67provide decorators to add functionality to views, those will probably68not work with async views because they will not await the function or be69awaitable. Other functions they provide will not be awaitable either and70will probably be blocking if called within an async view.7172Check the changelog of the extension you want to use to see if they've73implemented async support, or make a feature request or PR to them.747576Other event loops77-----------------7879At the moment Flask only supports :mod:`asyncio`. It's possible to80override :meth:`flask.Flask.ensure_sync` to change how async functions81are wrapped to use a different library.
modified:docs/design.rst+19 added
169 unmodified lines
170Also see the :doc:`/becomingbig` section of the documentation for some171inspiration for larger applications based on Flask.172173174Async/await and ASGI support175----------------------------176177Flask supports ``async`` coroutines for view functions by executing the178coroutine on a separate thread instead of using an event loop on the179main thread as an async-first (ASGI) framework would. This is necessary180for Flask to remain backwards compatible with extensions and code built181before ``async`` was introduced into Python. This compromise introduces182a performance cost compared with the ASGI frameworks, due to the183overhead of the threads.184185Due to how tied to WSGI Flask's code is, it's not clear if it's possible186to make the ``Flask`` class support ASGI and WSGI at the same time. Work187is currently being done in Werkzeug to work with ASGI, which may188eventually enable support in Flask as well.189190See :doc:`/async-await` for more discussion.191192193What Flask is, What Flask is Not194--------------------------------195196Flask will never have a database layer. It will not have a form library
12 unmodified lines
modified:docs/index.rst+1 added
57 unmodified lines
58 shell59 patterns/index60 deploying/index61 becomingbig62 async-await636465API Reference66-------------
25 unmodified lines
modified:requirements/tests.in+1 added
1pytest2asgiref3blinker4greenlet5python-dotenv
modified:requirements/tests.txt+2 added
2 unmodified lines
3# To update, run:4#5# pip-compile requirements/tests.in6#7asgiref==3.2.108 # via -r requirements/tests.in9attrs==20.3.010 # via pytest11blinker==1.412 # via -r requirements/tests.in
18 unmodified lines
modified:src/flask/app.py+19 added-3 removed
1import os2import sys3import weakref4from datetime import timedelta5from inspect import iscoroutinefunction6from itertools import chain7from threading import Lock89from werkzeug.datastructures import Headers
24 unmodified lines
34from .helpers import get_env35from .helpers import get_flashed_messages36from .helpers import get_load_dotenv37from .helpers import locked_cached_property38from .helpers import run_async39from .helpers import url_for40from .json import jsonify41from .logging import create_logger42from .scaffold import _endpoint_from_view_func
1008 unmodified lines
1051 raise AssertionError(1052 "View function mapping is overwriting an existing"1053 f" endpoint function: {endpoint}"1054 )1053 self.view_functions[endpoint] = view_func1055 self.view_functions[endpoint] = self.ensure_sync(view_func)10561057 @setupmethod1058 def template_filter(self, name=None):1059 """A decorator that is used to register custom template filter.
106 unmodified lines
1166 value is ignored.11671168 .. versionadded:: 0.81169 """1168 self.before_first_request_funcs.append(f)1170 self.before_first_request_funcs.append(self.ensure_sync(f))1171 return f11721173 @setupmethod1174 def teardown_appcontext(self, f):
24 unmodified lines
1199 The return values of teardown functions are ignored.12001201 .. versionadded:: 0.91202 """1201 self.teardown_appcontext_funcs.append(f)1203 self.teardown_appcontext_funcs.append(self.ensure_sync(f))1204 return f12051206 @setupmethod1207 def shell_context_processor(self, f):
310 unmodified lines
1518 .. versionadded:: 0.101519 """1520 return False15211522 def ensure_sync(self, func):1523 """Ensure that the function is synchronous for WSGI workers.1524 Plain ``def`` functions are returned as-is. ``async def``1525 functions are wrapped to run and wait for the response.15261527 Override this method to change how the app runs async views.15281529 .. versionadded:: 2.01530 """1531 if iscoroutinefunction(func):1532 return run_async(func)15331534 return func15351536 def make_response(self, rv):1537 """Convert the return value from a view function to an instance of1538 :attr:`response_class`.1539
433 unmodified lines
modified:src/flask/blueprints.py+51 added-13 removed
1from collections import defaultdict2from functools import update_wrapper34from .scaffold import _endpoint_from_view_func5from .scaffold import _sentinel
229 unmodified lines
235236 # Merge blueprint data into parent.237 if first_registration:238238 def extend(bp_dict, parent_dict):239 def extend(bp_dict, parent_dict, ensure_sync=False):240 for key, values in bp_dict.items():241 key = self.name if key is None else f"{self.name}.{key}"242243 if ensure_sync:244 values = [app.ensure_sync(func) for func in values]245246 parent_dict[key].extend(values)247243 def update(bp_dict, parent_dict):244 for key, value in bp_dict.items():245 key = self.name if key is None else f"{self.name}.{key}"246 parent_dict[key] = value248 for key, value in self.error_handler_spec.items():249 key = self.name if key is None else f"{self.name}.{key}"250 value = defaultdict(251 dict,252 {253 code: {254 exc_class: app.ensure_sync(func)255 for exc_class, func in code_values.items()256 }257 for code, code_values in value.items()258 },259 )260 app.error_handler_spec[key] = value261248 app.view_functions.update(self.view_functions)249 extend(self.before_request_funcs, app.before_request_funcs)250 extend(self.after_request_funcs, app.after_request_funcs)251 extend(self.teardown_request_funcs, app.teardown_request_funcs)262 for endpoint, func in self.view_functions.items():263 app.view_functions[endpoint] = app.ensure_sync(func)264265 extend(266 self.before_request_funcs, app.before_request_funcs, ensure_sync=True267 )268 extend(self.after_request_funcs, app.after_request_funcs, ensure_sync=True)269 extend(270 self.teardown_request_funcs,271 app.teardown_request_funcs,272 ensure_sync=True,273 )274 extend(self.url_default_functions, app.url_default_functions)275 extend(self.url_value_preprocessors, app.url_value_preprocessors)276 extend(self.template_context_processors, app.template_context_processors)255 update(self.error_handler_spec, app.error_handler_spec)277278 for deferred in self.deferred_functions:279 deferred(state)280
119 unmodified lines
400 """Like :meth:`Flask.before_request`. Such a function is executed401 before each request, even if outside of a blueprint.402 """403 self.record_once(383 lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)404 lambda s: s.app.before_request_funcs.setdefault(None, []).append(405 s.app.ensure_sync(f)406 )407 )408 return f409410 def before_app_first_request(self, f):411 """Like :meth:`Flask.before_first_request`. Such a function is412 executed before the first request to the application.413 """391 self.record_once(lambda s: s.app.before_first_request_funcs.append(f))414 self.record_once(415 lambda s: s.app.before_first_request_funcs.append(s.app.ensure_sync(f))416 )417 return f418419 def after_app_request(self, f):420 """Like :meth:`Flask.after_request` but for a blueprint. Such a function421 is executed after each request, even if outside of the blueprint.422 """423 self.record_once(399 lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)424 lambda s: s.app.after_request_funcs.setdefault(None, []).append(425 s.app.ensure_sync(f)426 )427 )428 return f429430 def teardown_app_request(self, f):
38 unmodified lines
469 self.record_once(470 lambda s: s.app.url_default_functions.setdefault(None, []).append(f)471 )472 return f473474 def ensure_sync(self, f):475 """Ensure the function is synchronous.476477 Override if you would like custom async to sync behaviour in478 this blueprint. Otherwise the app's479 :meth:`~flask.Flask.ensure_sync` is used.480481 .. versionadded:: 2.0482 """483 return f
modified:src/flask/helpers.py+49 added
1import os2import socket3import warnings4from functools import update_wrapper5from functools import wraps6from threading import RLock78import werkzeug.utils9from werkzeug.exceptions import NotFound10from werkzeug.local import ContextVar11from werkzeug.routing import BuildError12from werkzeug.urls import url_quote1314from .globals import _app_ctx_stack
715 unmodified lines
730 else:731 return True732733 return False734735736def run_async(func):737 """Return a sync function that will run the coroutine function *func*."""738 try:739 from asgiref.sync import async_to_sync740 except ImportError:741 raise RuntimeError(742 "Install Flask with the 'async' extra in order to use async views."743 )744745 # Check that Werkzeug isn't using its fallback ContextVar class.746 if ContextVar.__module__ == "werkzeug.local":747 raise RuntimeError(748 "Async cannot be used with this combination of Python & Greenlet versions."749 )750751 @wraps(func)752 def outer(*args, **kwargs):753 """This function grabs the current context for the inner function.754755 This is similar to the copy_current_xxx_context functions in the756 ctx module, except it has an async inner.757 """758 ctx = None759760 if _request_ctx_stack.top is not None:761 ctx = _request_ctx_stack.top.copy()762763 @wraps(func)764 async def inner(*a, **k):765 """This restores the context before awaiting the func.766767 This is required as the function must be awaited within the768 context. Only calling ``func`` (as per the769 ``copy_current_xxx_context`` functions) doesn't work as the770 with block will close before the coroutine is awaited.771 """772 if ctx is not None:773 with ctx:774 return await func(*a, **k)775 else:776 return await func(*a, **k)777778 return async_to_sync(inner)(*args, **kwargs)779780 return outer
modified:src/flask/scaffold.py+8 added-5 removed
482 unmodified lines
483 function.484 """485486 def decorator(f):487 self.view_functions[endpoint] = f487 self.view_functions[endpoint] = self.ensure_sync(f)488 return f489490 return decorator491
15 unmodified lines
507 a non-``None`` value, the value is handled as if it was the508 return value from the view, and further request handling is509 stopped.510 """511 self.before_request_funcs[None].append(f)511 self.before_request_funcs.setdefault(None, []).append(self.ensure_sync(f))512 return f513514 @setupmethod515 def after_request(self, f):
7 unmodified lines
523 ``after_request`` functions will not be called. Therefore, this524 should not be used for actions that must execute, such as to525 close resources. Use :meth:`teardown_request` for that.526 """527 self.after_request_funcs[None].append(f)527 self.after_request_funcs.setdefault(None, []).append(self.ensure_sync(f))528 return f529530 @setupmethod531 def teardown_request(self, f):
30 unmodified lines
562 immediately. Instead it will keep it alive so that the interactive563 debugger can still access it. This behavior can be controlled564 by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.565 """566 self.teardown_request_funcs[None].append(f)566 self.teardown_request_funcs.setdefault(None, []).append(self.ensure_sync(f))567 return f568569 @setupmethod570 def context_processor(self, f):
87 unmodified lines
658 " code. Use a subclass of HTTPException with that code"659 " instead."660 )661662 self.error_handler_spec[None][code][exc_class] = f662 self.error_handler_spec[None][code][exc_class] = self.ensure_sync(f)663664 @staticmethod665 def _get_exc_class_and_code(exc_class_or_code):666 """Get the exception class being handled. For HTTP status codes
16 unmodified lines
683 return exc_class, exc_class.code684 else:685 return exc_class, None686687 def ensure_sync(self, func):688 raise NotImplementedError()689690691def _endpoint_from_view_func(view_func):692 """Internal helper that returns the default endpoint for a given693 function. This always is the function name.694 """
170 unmodified lines
added:tests/test_async.py+139 added
1import asyncio2import sys34import pytest56from flask import Blueprint7from flask import Flask8from flask import request9from flask.helpers import run_async1011pytest.importorskip("asgiref")121314class AppError(Exception):15 pass161718class BlueprintError(Exception):19 pass202122@pytest.fixture(name="async_app")23def _async_app():24 app = Flask(__name__)2526 @app.route("/", methods=["GET", "POST"])27 async def index():28 await asyncio.sleep(0)29 return request.method3031 @app.errorhandler(AppError)32 async def handle(_):33 return "", 4123435 @app.route("/error")36 async def error():37 raise AppError()3839 blueprint = Blueprint("bp", __name__)4041 @blueprint.route("/", methods=["GET", "POST"])42 async def bp_index():43 await asyncio.sleep(0)44 return request.method4546 @blueprint.errorhandler(BlueprintError)47 async def bp_handle(_):48 return "", 4124950 @blueprint.route("/error")51 async def bp_error():52 raise BlueprintError()5354 app.register_blueprint(blueprint, url_prefix="/bp")5556 return app575859@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")60@pytest.mark.parametrize("path", ["/", "/bp/"])61def test_async_route(path, async_app):62 test_client = async_app.test_client()63 response = test_client.get(path)64 assert b"GET" in response.get_data()65 response = test_client.post(path)66 assert b"POST" in response.get_data()676869@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")70@pytest.mark.parametrize("path", ["/error", "/bp/error"])71def test_async_error_handler(path, async_app):72 test_client = async_app.test_client()73 response = test_client.get(path)74 assert response.status_code == 412757677@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")78def test_async_before_after_request():79 app_first_called = False80 app_before_called = False81 app_after_called = False82 bp_before_called = False83 bp_after_called = False8485 app = Flask(__name__)8687 @app.route("/")88 def index():89 return ""9091 @app.before_first_request92 async def before_first():93 nonlocal app_first_called94 app_first_called = True9596 @app.before_request97 async def before():98 nonlocal app_before_called99 app_before_called = True100101 @app.after_request102 async def after(response):103 nonlocal app_after_called104 app_after_called = True105 return response106107 blueprint = Blueprint("bp", __name__)108109 @blueprint.route("/")110 def bp_index():111 return ""112113 @blueprint.before_request114 async def bp_before():115 nonlocal bp_before_called116 bp_before_called = True117118 @blueprint.after_request119 async def bp_after(response):120 nonlocal bp_after_called121 bp_after_called = True122 return response123124 app.register_blueprint(blueprint, url_prefix="/bp")125126 test_client = app.test_client()127 test_client.get("/")128 assert app_first_called129 assert app_before_called130 assert app_after_called131 test_client.get("/bp/")132 assert bp_before_called133 assert bp_after_called134135136@pytest.mark.skipif(sys.version_info >= (3, 7), reason="should only raise Python < 3.7")137def test_async_runtime_error():138 with pytest.raises(RuntimeError):139 run_async(None)
modified:CHANGES.rst+2 added
65 unmodified lines
66- Use Jinja's implementation of the ``|tojson`` filter. :issue:`3881`67- Add route decorators for common HTTP methods. For example,68 ``@app.post("/login")`` is a shortcut for69 ``@app.route("/login", methods=["POST"])``. :pr:`3907`70- Support async views, error handlers, before and after request, and71 teardown functions. :pr:`3412`727374Version 1.1.275-------------
1011 unmodified lines
modified:setup.py+4 added-1 removed
7 unmodified lines
8 "Jinja2>=2.10.1",9 "itsdangerous>=0.24",10 "click>=5.1",11 ],12 extras_require={"dotenv": ["python-dotenv"]},12 extras_require={13 "async": ["asgiref>=3.2"],14 "dotenv": ["python-dotenv"],15 },16)
modified:tox.ini+4 added-1 removed
23 unmodified lines
24skip_install = true25commands = pre-commit run --all-files --show-diff-on-failure2627[testenv:docs]28deps =28deps = -r requirements/docs.txt29 -r requirements/docs.txt3031 https://github.com/pallets/werkzeug/archive/master.tar.gz32commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html