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
Provenance
- Commit
1a79d2d- Tree
67b7b63- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
9ddef01- Parent 2
dc3e9c0
13 files changed+380 added−23 removed
added:docs/async-await.rst+81 added
1+.. _async_await:2+3+Using ``async`` and ``await``4+=============================5+6+.. versionadded:: 2.07+8+Routes, error handlers, before request, after request, and teardown9+functions can all be coroutine functions if Flask is installed with the10+``async`` extra (``pip install flask[async]``). This allows views to be11+defined with ``async def`` and use ``await``.12+13+.. code-block:: python14+15+ @app.route("/get-data")16+ async def get_data():17+ data = await async_db_query(...)18+ return jsonify(data)19+20+21+Performance22+-----------23+24+Async functions require an event loop to run. Flask, as a WSGI25+application, uses one worker to handle one request/response cycle.26+When a request comes in to an async view, Flask will start an event loop27+in a thread, run the view function there, then return the result.28+29+Each request still ties up one worker, even for async views. The upside30+is that you can run async code within a view, for example to make31+multiple concurrent database queries, HTTP requests to an external API,32+etc. However, the number of requests your application can handle at one33+time will remain the same.34+35+**Async is not inherently faster than sync code.** Async is beneficial36+when performing concurrent IO-bound tasks, but will probably not improve37+CPU-bound tasks. Traditional Flask views will still be appropriate for38+most use cases, but Flask's async support enables writing and using39+code that wasn't possible natively before.40+41+42+When to use Quart instead43+-------------------------44+45+Flask's async support is less performant than async-first frameworks due46+to the way it is implemented. If you have a mainly async codebase it47+would make sense to consider `Quart`_. Quart is a reimplementation of48+Flask based on the `ASGI`_ standard instead of WSGI. This allows it to49+handle many concurrent requests, long running requests, and websockets50+without requiring individual worker processes or threads.51+52+It has also already been possible to run Flask with Gevent or Eventlet53+to get many of the benefits of async request handling. These libraries54+patch low-level Python functions to accomplish this, whereas ``async``/55+``await`` and ASGI use standard, modern Python capabilities. Deciding56+whether you should use Flask, Quart, or something else is ultimately up57+to understanding the specific needs of your project.58+59+.. _Quart: https://gitlab.com/pgjones/quart60+.. _ASGI: https://asgi.readthedocs.io/en/latest/61+62+63+Extensions64+----------65+66+Existing Flask extensions only expect views to be synchronous. If they67+provide decorators to add functionality to views, those will probably68+not work with async views because they will not await the function or be69+awaitable. Other functions they provide will not be awaitable either and70+will probably be blocking if called within an async view.71+72+Check the changelog of the extension you want to use to see if they've73+implemented async support, or make a feature request or PR to them.74+75+76+Other event loops77+-----------------78+79+At the moment Flask only supports :mod:`asyncio`. It's possible to80+override :meth:`flask.Flask.ensure_sync` to change how async functions81+are wrapped to use a different library.modified:docs/design.rst+19 added
169 unmodified lines170 Also see the :doc:`/becomingbig` section of the documentation for some171 inspiration for larger applications based on Flask.172 173 174+Async/await and ASGI support175+----------------------------176+177+Flask supports ``async`` coroutines for view functions by executing the178+coroutine on a separate thread instead of using an event loop on the179+main thread as an async-first (ASGI) framework would. This is necessary180+for Flask to remain backwards compatible with extensions and code built181+before ``async`` was introduced into Python. This compromise introduces182+a performance cost compared with the ASGI frameworks, due to the183+overhead of the threads.184+185+Due to how tied to WSGI Flask's code is, it's not clear if it's possible186+to make the ``Flask`` class support ASGI and WSGI at the same time. Work187+is currently being done in Werkzeug to work with ASGI, which may188+eventually enable support in Flask as well.189+190+See :doc:`/async-await` for more discussion.191+192+193 What Flask is, What Flask is Not194 --------------------------------195 196 Flask will never have a database layer. It will not have a form library12 unmodified linesmodified:docs/index.rst+1 added
57 unmodified lines58 shell59 patterns/index60 deploying/index61 becomingbig62+ async-await63 64 65 API Reference66 -------------25 unmodified linesmodified:requirements/tests.in+1 added
1 pytest2+asgiref3 blinker4 greenlet5 python-dotenvmodified:requirements/tests.txt+2 added
2 unmodified lines3 # To update, run:4 #5 # pip-compile requirements/tests.in6 #7+asgiref==3.2.108+ # via -r requirements/tests.in9 attrs==20.3.010 # via pytest11 blinker==1.412 # via -r requirements/tests.in18 unmodified linesmodified:src/flask/app.py+19 added-3 removed
1 import os2 import sys3 import weakref4 from datetime import timedelta5+from inspect import iscoroutinefunction6 from itertools import chain7 from threading import Lock8 9 from werkzeug.datastructures import Headers24 unmodified lines34 from .helpers import get_env35 from .helpers import get_flashed_messages36 from .helpers import get_load_dotenv37 from .helpers import locked_cached_property38+from .helpers import run_async39 from .helpers import url_for40 from .json import jsonify41 from .logging import create_logger42 from .scaffold import _endpoint_from_view_func1008 unmodified lines1051 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)1056 1057 @setupmethod1058 def template_filter(self, name=None):1059 """A decorator that is used to register custom template filter.106 unmodified lines1166 value is ignored.1167 1168 .. versionadded:: 0.81169 """1168- self.before_first_request_funcs.append(f)1170+ self.before_first_request_funcs.append(self.ensure_sync(f))1171 return f1172 1173 @setupmethod1174 def teardown_appcontext(self, f):24 unmodified lines1199 The return values of teardown functions are ignored.1200 1201 .. versionadded:: 0.91202 """1201- self.teardown_appcontext_funcs.append(f)1203+ self.teardown_appcontext_funcs.append(self.ensure_sync(f))1204 return f1205 1206 @setupmethod1207 def shell_context_processor(self, f):310 unmodified lines1518 .. versionadded:: 0.101519 """1520 return False1521 1522+ 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.1526+1527+ Override this method to change how the app runs async views.1528+1529+ .. versionadded:: 2.01530+ """1531+ if iscoroutinefunction(func):1532+ return run_async(func)1533+1534+ return func1535+1536 def make_response(self, rv):1537 """Convert the return value from a view function to an instance of1538 :attr:`response_class`.1539 433 unmodified linesmodified:src/flask/blueprints.py+51 added-13 removed
1+from collections import defaultdict2 from functools import update_wrapper3 4 from .scaffold import _endpoint_from_view_func5 from .scaffold import _sentinel229 unmodified lines235 236 # Merge blueprint data into parent.237 if first_registration:238 238- 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}"242+243+ if ensure_sync:244+ values = [app.ensure_sync(func) for func in values]245+246 parent_dict[key].extend(values)247 243- 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] = value261 248- 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)264+265+ 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)277 278 for deferred in self.deferred_functions:279 deferred(state)280 119 unmodified lines400 """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 f409 410 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 f418 419 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 f429 430 def teardown_app_request(self, f):38 unmodified lines469 self.record_once(470 lambda s: s.app.url_default_functions.setdefault(None, []).append(f)471 )472 return f473+474+ def ensure_sync(self, f):475+ """Ensure the function is synchronous.476+477+ Override if you would like custom async to sync behaviour in478+ this blueprint. Otherwise the app's479+ :meth:`~flask.Flask.ensure_sync` is used.480+481+ .. versionadded:: 2.0482+ """483+ return fmodified:src/flask/helpers.py+49 added
1 import os2 import socket3 import warnings4 from functools import update_wrapper5+from functools import wraps6 from threading import RLock7 8 import werkzeug.utils9 from werkzeug.exceptions import NotFound10+from werkzeug.local import ContextVar11 from werkzeug.routing import BuildError12 from werkzeug.urls import url_quote13 14 from .globals import _app_ctx_stack715 unmodified lines730 else:731 return True732 733 return False734+735+736+def 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+ )744+745+ # 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+ )750+751+ @wraps(func)752+ def outer(*args, **kwargs):753+ """This function grabs the current context for the inner function.754+755+ This is similar to the copy_current_xxx_context functions in the756+ ctx module, except it has an async inner.757+ """758+ ctx = None759+760+ if _request_ctx_stack.top is not None:761+ ctx = _request_ctx_stack.top.copy()762+763+ @wraps(func)764+ async def inner(*a, **k):765+ """This restores the context before awaiting the func.766+767+ 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)777+778+ return async_to_sync(inner)(*args, **kwargs)779+780+ return outermodified:src/flask/scaffold.py+8 added-5 removed
482 unmodified lines483 function.484 """485 486 def decorator(f):487- self.view_functions[endpoint] = f487+ self.view_functions[endpoint] = self.ensure_sync(f)488 return f489 490 return decorator491 15 unmodified lines507 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 f513 514 @setupmethod515 def after_request(self, f):7 unmodified lines523 ``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 f529 530 @setupmethod531 def teardown_request(self, f):30 unmodified lines562 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 f568 569 @setupmethod570 def context_processor(self, f):87 unmodified lines658 " code. Use a subclass of HTTPException with that code"659 " instead."660 )661 662- self.error_handler_spec[None][code][exc_class] = f662+ self.error_handler_spec[None][code][exc_class] = self.ensure_sync(f)663 664 @staticmethod665 def _get_exc_class_and_code(exc_class_or_code):666 """Get the exception class being handled. For HTTP status codes16 unmodified lines683 return exc_class, exc_class.code684 else:685 return exc_class, None686 687+ def ensure_sync(self, func):688+ raise NotImplementedError()689 690+691 def _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 linesadded:tests/test_async.py+139 added
1+import asyncio2+import sys3+4+import pytest5+6+from flask import Blueprint7+from flask import Flask8+from flask import request9+from flask.helpers import run_async10+11+pytest.importorskip("asgiref")12+13+14+class AppError(Exception):15+ pass16+17+18+class BlueprintError(Exception):19+ pass20+21+22+@pytest.fixture(name="async_app")23+def _async_app():24+ app = Flask(__name__)25+26+ @app.route("/", methods=["GET", "POST"])27+ async def index():28+ await asyncio.sleep(0)29+ return request.method30+31+ @app.errorhandler(AppError)32+ async def handle(_):33+ return "", 41234+35+ @app.route("/error")36+ async def error():37+ raise AppError()38+39+ blueprint = Blueprint("bp", __name__)40+41+ @blueprint.route("/", methods=["GET", "POST"])42+ async def bp_index():43+ await asyncio.sleep(0)44+ return request.method45+46+ @blueprint.errorhandler(BlueprintError)47+ async def bp_handle(_):48+ return "", 41249+50+ @blueprint.route("/error")51+ async def bp_error():52+ raise BlueprintError()53+54+ app.register_blueprint(blueprint, url_prefix="/bp")55+56+ return app57+58+59+@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")60+@pytest.mark.parametrize("path", ["/", "/bp/"])61+def 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()67+68+69+@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")70+@pytest.mark.parametrize("path", ["/error", "/bp/error"])71+def 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 == 41275+76+77+@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")78+def 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 = False84+85+ app = Flask(__name__)86+87+ @app.route("/")88+ def index():89+ return ""90+91+ @app.before_first_request92+ async def before_first():93+ nonlocal app_first_called94+ app_first_called = True95+96+ @app.before_request97+ async def before():98+ nonlocal app_before_called99+ app_before_called = True100+101+ @app.after_request102+ async def after(response):103+ nonlocal app_after_called104+ app_after_called = True105+ return response106+107+ blueprint = Blueprint("bp", __name__)108+109+ @blueprint.route("/")110+ def bp_index():111+ return ""112+113+ @blueprint.before_request114+ async def bp_before():115+ nonlocal bp_before_called116+ bp_before_called = True117+118+ @blueprint.after_request119+ async def bp_after(response):120+ nonlocal bp_after_called121+ bp_after_called = True122+ return response123+124+ app.register_blueprint(blueprint, url_prefix="/bp")125+126+ 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_called134+135+136+@pytest.mark.skipif(sys.version_info >= (3, 7), reason="should only raise Python < 3.7")137+def test_async_runtime_error():138+ with pytest.raises(RuntimeError):139+ run_async(None)modified:CHANGES.rst+2 added
65 unmodified lines66 - 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`72 73 74 Version 1.1.275 -------------1011 unmodified linesmodified:setup.py+4 added-1 removed
7 unmodified lines8 "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 lines24 skip_install = true25 commands = pre-commit run --all-files --show-diff-on-failure26 27 [testenv:docs]28+deps =28-deps = -r requirements/docs.txt29+ -r requirements/docs.txt30+31+ https://github.com/pallets/werkzeug/archive/master.tar.gz32 commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html