Add `async` support
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This allows for async functions to be passed to the Flask class instance, for example as a view function, @app.route("/") async def index(): return "Async hello" this comes with a cost though of poorer performance than using the sync equivalent. asgiref is the standard way to run async code within a sync context, and is used in Django making it a safe and sane choice for this.
authored by pgjones · committed by David Lord · parent 85b8fab · Browse files · 11 files·+165 added−9 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+165 added−9 removed
- tests:+33 added−0 removed
- other:+132 added−9 removed
Provenance
- Commit
6979265- Tree
7f07086- Author
pgjones <philip.graham.jones@googlemail.com>- Committer
David Lord <davidism@gmail.com>- Parent
85b8fab
11 files changed+165 added−9 removed
added:docs/async_await.rst+46 added
1+.. _async_await:2+3+Using async and await4+=====================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 with10+the ``async`` extra (``pip install flask[async]``). This allows code11+such as,12+13+.. code-block:: python14+15+ @app.route("/")16+ async def index():17+ return await ...18+19+including the usage of any asyncio based libraries.20+21+22+When to use Quart instead23+-------------------------24+25+Flask's ``async/await`` support is less performant than async first26+frameworks due to the way it is implemented. Therefore if you have a27+mainly async codebase it would make sense to consider `Quart28+<https://gitlab.com/pgjones/quart>`_. Quart is a reimplementation of29+the Flask using ``async/await`` based on the ASGI standard (Flask is30+based on the WSGI standard).31+32+33+Decorators34+----------35+36+Decorators designed for Flask, such as those in Flask extensions are37+unlikely to work. This is because the decorator will not await the38+coroutine function nor will they themselves be awaitable.39+40+41+Other event loops42+-----------------43+44+At the moment Flask only supports asyncio - the45+:meth:`flask.Flask.ensure_sync` should be overridden to support46+alternative event loops.modified:docs/design.rst+12 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, and certain178+others by executing the coroutine on a seperate thread instead of179+utilising an event loop on the main thread as an async first (ASGI)180+frameworks would. This is necessary for Flask to remain backwards181+compatibility with extensions and code built before ``async`` was182+introduced into Python. This compromise introduces a performance cost183+compared with the ASGI frameworks, due to the overhead of the threads.184+185+186 What Flask is, What Flask is Not187 --------------------------------188 189 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+3 added-3 removed
1048 unmodified lines1049 raise AssertionError(1050 "View function mapping is overwriting an existing"1051 f" endpoint function: {endpoint}"1052 )1053- self.view_functions[endpoint] = view_func1053+ self.view_functions[endpoint] = self.ensure_sync(view_func)1054 1055 @setupmethod1056 def template_filter(self, name=None):1057 """A decorator that is used to register custom template filter.106 unmodified lines1164 value is ignored.1165 1166 .. versionadded:: 0.81167 """1168- self.before_first_request_funcs.append(f)1168+ self.before_first_request_funcs.append(self.ensure_sync(f))1169 return f1170 1171 @setupmethod1172 def teardown_appcontext(self, f):24 unmodified lines1197 The return values of teardown functions are ignored.1198 1199 .. versionadded:: 0.91200 """1201- self.teardown_appcontext_funcs.append(f)1201+ self.teardown_appcontext_funcs.append(self.ensure_sync(f))1202 return f1203 1204 @setupmethod1205 def shell_context_processor(self, f):751 unmodified linesmodified:src/flask/helpers.py+41 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 NotFound719 unmodified lines729 else:730 return True731 732 return False733+734+735+def run_async(func):736+ """Return a sync function that will run the coroutine function *func*."""737+ try:738+ from asgiref.sync import async_to_sync739+ except ImportError:740+ raise RuntimeError(741+ "Install Flask with the 'async' extra in order to use async views."742+ )743+744+ @wraps(func)745+ def outer(*args, **kwargs):746+ """This function grabs the current context for the inner function.747+748+ This is similar to the copy_current_xxx_context functions in the749+ ctx module, except it has an async inner.750+ """751+ ctx = None752+ if _request_ctx_stack.top is not None:753+ ctx = _request_ctx_stack.top.copy()754+755+ @wraps(func)756+ async def inner(*a, **k):757+ """This restores the context before awaiting the func.758+759+ This is required as the func must be awaited within the760+ context. Simply calling func (as per the761+ copy_current_xxx_context functions) doesn't work as the762+ with block will close before the coroutine is awaited.763+ """764+ if ctx is not None:765+ with ctx:766+ return await func(*a, **k)767+ else:768+ return await func(*a, **k)769+770+ return async_to_sync(inner)(*args, **kwargs)771+772+ return outermodified:src/flask/scaffold.py+20 added-5 removed
2 unmodified lines3 import pkgutil4 import sys5 from collections import defaultdict6 from functools import update_wrapper7+from inspect import iscoroutinefunction8 9 from jinja2 import FileSystemLoader10 from werkzeug.exceptions import default_exceptions11 from werkzeug.exceptions import HTTPException12 13 from .cli import AppGroup14 from .globals import current_app15 from .helpers import locked_cached_property16+from .helpers import run_async17 from .helpers import send_from_directory18 from .templating import _default_template_ctx_processor19 20 # a singleton sentinel value for parameter defaults464 unmodified lines485 function.486 """487 488 def decorator(f):487- self.view_functions[endpoint] = f489+ self.view_functions[endpoint] = self.ensure_sync(f)490 return f491 492 return decorator493 15 unmodified lines509 a non-``None`` value, the value is handled as if it was the510 return value from the view, and further request handling is511 stopped.512 """511- self.before_request_funcs[None].append(f)513+ self.before_request_funcs.setdefault(None, []).append(self.ensure_sync(f))514 return f515 516 @setupmethod517 def after_request(self, f):7 unmodified lines525 ``after_request`` functions will not be called. Therefore, this526 should not be used for actions that must execute, such as to527 close resources. Use :meth:`teardown_request` for that.528 """527- self.after_request_funcs[None].append(f)529+ self.after_request_funcs.setdefault(None, []).append(self.ensure_sync(f))530 return f531 532 @setupmethod533 def teardown_request(self, f):30 unmodified lines564 immediately. Instead it will keep it alive so that the interactive565 debugger can still access it. This behavior can be controlled566 by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.567 """566- self.teardown_request_funcs[None].append(f)568+ self.teardown_request_funcs.setdefault(None, []).append(self.ensure_sync(f))569 return f570 571 @setupmethod572 def context_processor(self, f):87 unmodified lines660 " code. Use a subclass of HTTPException with that code"661 " instead."662 )663 662- self.error_handler_spec[None][code][exc_class] = f664+ self.error_handler_spec[None][code][exc_class] = self.ensure_sync(f)665 666 @staticmethod667 def _get_exc_class_and_code(exc_class_or_code):668 """Get the exception class being handled. For HTTP status codes16 unmodified lines685 return exc_class, exc_class.code686 else:687 return exc_class, None688 689+ def ensure_sync(self, func):690+ """Ensure that the returned function is sync and calls the async func.691 692+ .. versionadded:: 2.0693+694+ Override if you wish to change how asynchronous functions are695+ run.696+ """697+ if iscoroutinefunction(func):698+ return run_async(func)699+ else:700+ return func701+702+703 def _endpoint_from_view_func(view_func):704 """Internal helper that returns the default endpoint for a given705 function. This always is the function name.706 """170 unmodified linesadded:tests/test_async.py+33 added
1+import asyncio2+3+import pytest4+5+from flask import abort6+from flask import Flask7+from flask import request8+9+10+@pytest.fixture(name="async_app")11+def _async_app():12+ app = Flask(__name__)13+14+ @app.route("/", methods=["GET", "POST"])15+ async def index():16+ await asyncio.sleep(0)17+ return request.method18+19+ @app.route("/error")20+ async def error():21+ abort(412)22+23+ return app24+25+26+def test_async_request_context(async_app):27+ test_client = async_app.test_client()28+ response = test_client.get("/")29+ assert b"GET" in response.get_data()30+ response = test_client.post("/")31+ assert b"POST" in response.get_data()32+ response = test_client.get("/error")33+ assert response.status_code == 412modified: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 )