Merge pull request #3989 from pgjones/async
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Async improvements
authored by David Lord · committed by GitHub · parents 188f478, 2889da6 · Browse files · 6 files·+74 added−108 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+74 added−108 removed
- tests:+2 added−2 removed
- other:+72 added−106 removed
Provenance
- Commit
47f0e79- Tree
4cc2d79- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
188f478- Parent 2
2889da6
6 files changed+74 added−108 removed
modified:docs/async-await.rst+15 added
90 unmodified lines91 not work with async views because they will not await the function or be92 awaitable. Other functions they provide will not be awaitable either and93 will probably be blocking if called within an async view.94 95+Extension authors can support async functions by utilising the96+:meth:`flask.Flask.ensure_sync` method. For example, if the extension97+provides a view function decorator add ``ensure_sync`` before calling98+the decorated function,99+100+.. code-block:: python101+102+ def extension(func):103+ @wraps(func)104+ def wrapper(*args, **kwargs):105+ ... # Extension logic106+ return current_app.ensure_sync(func)(*args, **kwargs)107+108+ return wrapper109+110 Check the changelog of the extension you want to use to see if they've111 implemented async support, or make a feature request or PR to them.112 113 6 unmodified linesmodified:src/flask/app.py+44 added-16 removed
14 unmodified lines15 from werkzeug.exceptions import BadRequest16 from werkzeug.exceptions import BadRequestKeyError17 from werkzeug.exceptions import HTTPException18 from werkzeug.exceptions import InternalServerError19+from werkzeug.local import ContextVar20 from werkzeug.routing import BuildError21 from werkzeug.routing import Map22 from werkzeug.routing import MapAdapter23 from werkzeug.routing import RequestRedirect16 unmodified lines40 from .helpers import get_env41 from .helpers import get_flashed_messages42 from .helpers import get_load_dotenv43 from .helpers import locked_cached_property43-from .helpers import run_async44 from .helpers import url_for45 from .json import jsonify46 from .logging import create_logger47 from .scaffold import _endpoint_from_view_func1031 unmodified lines1079 1080 self.url_map.add(rule)1081 if view_func is not None:1082 old_func = self.view_functions.get(endpoint)1083- if getattr(old_func, "_flask_sync_wrapper", False):1084- old_func = old_func.__wrapped__ # type: ignore1083 if old_func is not None and old_func != view_func:1084 raise AssertionError(1085 "View function mapping is overwriting an existing"1086 f" endpoint function: {endpoint}"1087 )1090- self.view_functions[endpoint] = self.ensure_sync(view_func)1088+ self.view_functions[endpoint] = view_func1089 1090 @setupmethod1091 def template_filter(self, name: t.Optional[str] = None) -> t.Callable:1092 """A decorator that is used to register custom template filter.112 unmodified lines1205 value is ignored.1206 1207 .. versionadded:: 0.81208 """1211- self.before_first_request_funcs.append(self.ensure_sync(f))1209+ self.before_first_request_funcs.append(f)1210 return f1211 1212 @setupmethod1213 def teardown_appcontext(self, f: TeardownCallable) -> TeardownCallable:24 unmodified lines1238 The return values of teardown functions are ignored.1239 1240 .. versionadded:: 0.91241 """1244- self.teardown_appcontext_funcs.append(self.ensure_sync(f))1242+ self.teardown_appcontext_funcs.append(f)1243 return f1244 1245 @setupmethod1246 def shell_context_processor(self, f: t.Callable) -> t.Callable:58 unmodified lines1305 1306 handler = self._find_error_handler(e)1307 if handler is None:1308 return e1311- return handler(e)1309+ return self.ensure_sync(handler)(e)1310 1311 def trap_http_exception(self, e: Exception) -> bool:1312 """Checks if an HTTP exception should be trapped or not. By default1313 this will return ``False`` for all exceptions except for a bad request58 unmodified lines1372 1373 if handler is None:1374 raise1375 1378- return handler(e)1376+ return self.ensure_sync(handler)(e)1377 1378 def handle_exception(self, e: Exception) -> Response:1379 """Handle an exception that did not have an error handler1380 associated with it, or that was raised from an error handler.38 unmodified lines1419 server_error = InternalServerError(original_exception=e)1420 handler = self._find_error_handler(server_error)1421 1422 if handler is not None:1425- server_error = handler(server_error)1423+ server_error = self.ensure_sync(handler)(server_error)1424 1425 return self.finalize_request(server_error, from_error_handler=True)1426 1427 def log_exception(53 unmodified lines1481 and req.method == "OPTIONS"1482 ):1483 return self.make_default_options_response()1484 # otherwise dispatch to the handler for that endpoint1487- return self.view_functions[rule.endpoint](**req.view_args)1485+ return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)1486 1487 def full_dispatch_request(self) -> Response:1488 """Dispatches the request and on top of that performs request1489 pre and postprocessing as well as HTTP exception catching and52 unmodified lines1542 with self._before_request_lock:1543 if self._got_first_request:1544 return1545 for func in self.before_first_request_funcs:1548- func()1546+ self.ensure_sync(func)()1547 self._got_first_request = True1548 1549 def make_default_options_response(self) -> Response:1550 """This method is called to create the default ``OPTIONS`` response.27 unmodified lines1578 1579 .. versionadded:: 2.01580 """1581 if iscoroutinefunction(func):1584- return run_async(func)1582+ return self.async_to_sync(func)1583 1584 return func1585 1586+ def async_to_sync(1587+ self, func: t.Callable[..., t.Coroutine]1588+ ) -> t.Callable[..., t.Any]:1589+ """Return a sync function that will run the coroutine function.1590+1591+ .. code-block:: python1592+1593+ result = app.async_to_sync(func)(*args, **kwargs)1594+1595+ Override this method to change how the app converts async code1596+ to be synchronously callable.1597+1598+ .. versionadded:: 2.01599+ """1600+ try:1601+ from asgiref.sync import async_to_sync as asgiref_async_to_sync1602+ except ImportError:1603+ raise RuntimeError(1604+ "Install Flask with the 'async' extra in order to use async views."1605+ )1606+1607+ # Check that Werkzeug isn't using its fallback ContextVar class.1608+ if ContextVar.__module__ == "werkzeug.local":1609+ raise RuntimeError(1610+ "Async cannot be used with this combination of Python "1611+ "and Greenlet versions."1612+ )1613+1614+ return asgiref_async_to_sync(func)1615+1616 def make_response(self, rv: ResponseReturnValue) -> Response:1617 """Convert the return value from a view function to an instance of1618 :attr:`response_class`.1619 214 unmodified lines1834 for bp in self._request_blueprints():1835 if bp in self.before_request_funcs:1836 funcs = chain(funcs, self.before_request_funcs[bp])1837 for func in funcs:1810- rv = func()1838+ rv = self.ensure_sync(func)()1839 if rv is not None:1840 return rv1841 1842 return None18 unmodified lines1861 funcs = chain(funcs, reversed(self.after_request_funcs[bp]))1862 if None in self.after_request_funcs:1863 funcs = chain(funcs, reversed(self.after_request_funcs[None]))1864 for handler in funcs:1837- response = handler(response)1865+ response = self.ensure_sync(handler)(response)1866 if not self.session_interface.is_null_session(ctx.session):1867 self.session_interface.save_session(self, ctx.session, response)1868 return response1869 28 unmodified lines1898 for bp in self._request_blueprints():1899 if bp in self.teardown_request_funcs:1900 funcs = chain(funcs, reversed(self.teardown_request_funcs[bp]))1901 for func in funcs:1874- func(exc)1902+ self.ensure_sync(func)(exc)1903 request_tearing_down.send(self, exc=exc)1904 1905 def do_teardown_appcontext(1906 self, exc: t.Optional[BaseException] = _sentinel # type: ignore14 unmodified lines1921 """1922 if exc is _sentinel:1923 exc = sys.exc_info()[1]1924 for func in reversed(self.teardown_appcontext_funcs):1897- func(exc)1925+ self.ensure_sync(func)(exc)1926 appcontext_tearing_down.send(self, exc=exc)1927 1928 def app_context(self) -> AppContext:1929 """Create an :class:`~flask.ctx.AppContext`. Use as a ``with``146 unmodified linesmodified:src/flask/blueprints.py+8 added-32 removed
290 unmodified lines291 292 # Merge blueprint data into parent.293 if first_registration:294 295- def extend(bp_dict, parent_dict, ensure_sync=False):295+ def extend(bp_dict, parent_dict):296 for key, values in bp_dict.items():297 key = self.name if key is None else f"{self.name}.{key}"298 299- if ensure_sync:300- values = [app.ensure_sync(func) for func in values]301-299 parent_dict[key].extend(values)300 301 for key, value in self.error_handler_spec.items():302 key = self.name if key is None else f"{self.name}.{key}"303 value = defaultdict(304 dict,305 {306 code: {310- exc_class: app.ensure_sync(func)311- for exc_class, func in code_values.items()307+ exc_class: func for exc_class, func in code_values.items()308 }309 for code, code_values in value.items()310 },311 )312 app.error_handler_spec[key] = value313 314 for endpoint, func in self.view_functions.items():319- app.view_functions[endpoint] = app.ensure_sync(func)315+ app.view_functions[endpoint] = func316 317+ extend(self.before_request_funcs, app.before_request_funcs)318+ extend(self.after_request_funcs, app.after_request_funcs)319 extend(322- self.before_request_funcs, app.before_request_funcs, ensure_sync=True323- )324- extend(self.after_request_funcs, app.after_request_funcs, ensure_sync=True)325- extend(320 self.teardown_request_funcs,321 app.teardown_request_funcs,328- ensure_sync=True,322 )323 extend(self.url_default_functions, app.url_default_functions)324 extend(self.url_value_preprocessors, app.url_value_preprocessors)325 extend(self.template_context_processors, app.template_context_processors)144 unmodified lines470 """Like :meth:`Flask.before_request`. Such a function is executed471 before each request, even if outside of a blueprint.472 """473 self.record_once(481- lambda s: s.app.before_request_funcs.setdefault(None, []).append(482- s.app.ensure_sync(f)483- )474+ lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)475 )476 return f477 478 def before_app_first_request(1 unmodified line480 ) -> BeforeRequestCallable:481 """Like :meth:`Flask.before_first_request`. Such a function is482 executed before the first request to the application.483 """493- self.record_once(494- lambda s: s.app.before_first_request_funcs.append(s.app.ensure_sync(f))495- )484+ self.record_once(lambda s: s.app.before_first_request_funcs.append(f))485 return f486 487 def after_app_request(self, f: AfterRequestCallable) -> AfterRequestCallable:488 """Like :meth:`Flask.after_request` but for a blueprint. Such a function489 is executed after each request, even if outside of the blueprint.490 """491 self.record_once(503- lambda s: s.app.after_request_funcs.setdefault(None, []).append(504- s.app.ensure_sync(f)505- )492+ lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)493 )494 return f495 496 def teardown_app_request(self, f: TeardownCallable) -> TeardownCallable:42 unmodified lines539 self.record_once(540 lambda s: s.app.url_default_functions.setdefault(None, []).append(f)541 )542 return f556-557- def ensure_sync(self, f: t.Callable) -> t.Callable:558- """Ensure the function is synchronous.559-560- Override if you would like custom async to sync behaviour in561- this blueprint. Otherwise the app's562- :meth:`~flask.Flask.ensure_sync` is used.563-564- .. versionadded:: 2.0565- """566- return fmodified:src/flask/helpers.py-50 removed
4 unmodified lines5 import typing as t6 import warnings7 from datetime import timedelta8 from functools import update_wrapper9-from functools import wraps9 from threading import RLock10 11 import werkzeug.utils12 from werkzeug.exceptions import NotFound14-from werkzeug.local import ContextVar13 from werkzeug.routing import BuildError14 from werkzeug.urls import url_quote15 16 from .globals import _app_ctx_stack781 unmodified lines798 else:799 return True800 801 return False804-805-806-def run_async(func: t.Callable[..., t.Coroutine]) -> t.Callable[..., t.Any]:807- """Return a sync function that will run the coroutine function *func*."""808- try:809- from asgiref.sync import async_to_sync810- except ImportError:811- raise RuntimeError(812- "Install Flask with the 'async' extra in order to use async views."813- )814-815- # Check that Werkzeug isn't using its fallback ContextVar class.816- if ContextVar.__module__ == "werkzeug.local":817- raise RuntimeError(818- "Async cannot be used with this combination of Python & Greenlet versions."819- )820-821- @wraps(func)822- def outer(*args: t.Any, **kwargs: t.Any) -> t.Any:823- """This function grabs the current context for the inner function.824-825- This is similar to the copy_current_xxx_context functions in the826- ctx module, except it has an async inner.827- """828- ctx = None829-830- if _request_ctx_stack.top is not None:831- ctx = _request_ctx_stack.top.copy()832-833- @wraps(func)834- async def inner(*a: t.Any, **k: t.Any) -> t.Any:835- """This restores the context before awaiting the func.836-837- This is required as the function must be awaited within the838- context. Only calling ``func`` (as per the839- ``copy_current_xxx_context`` functions) doesn't work as the840- with block will close before the coroutine is awaited.841- """842- if ctx is not None:843- with ctx:844- return await func(*a, **k)845- else:846- return await func(*a, **k)847-848- return async_to_sync(inner)(*args, **kwargs)849-850- outer._flask_sync_wrapper = True # type: ignore851- return outermodified:src/flask/scaffold.py+5 added-8 removed
519 unmodified lines520 function.521 """522 523 def decorator(f):524- self.view_functions[endpoint] = self.ensure_sync(f)524+ self.view_functions[endpoint] = f525 return f526 527 return decorator528 15 unmodified lines544 a non-``None`` value, the value is handled as if it was the545 return value from the view, and further request handling is546 stopped.547 """548- self.before_request_funcs.setdefault(None, []).append(self.ensure_sync(f))548+ self.before_request_funcs.setdefault(None, []).append(f)549 return f550 551 @setupmethod552 def after_request(self, f: AfterRequestCallable) -> AfterRequestCallable:7 unmodified lines560 ``after_request`` functions will not be called. Therefore, this561 should not be used for actions that must execute, such as to562 close resources. Use :meth:`teardown_request` for that.563 """564- self.after_request_funcs.setdefault(None, []).append(self.ensure_sync(f))564+ self.after_request_funcs.setdefault(None, []).append(f)565 return f566 567 @setupmethod568 def teardown_request(self, f: TeardownCallable) -> TeardownCallable:30 unmodified lines599 immediately. Instead it will keep it alive so that the interactive600 debugger can still access it. This behavior can be controlled601 by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.602 """603- self.teardown_request_funcs.setdefault(None, []).append(self.ensure_sync(f))603+ self.teardown_request_funcs.setdefault(None, []).append(f)604 return f605 606 @setupmethod607 def context_processor(97 unmodified lines705 " code. Use a subclass of HTTPException with that code"706 " instead."707 )708 709- self.error_handler_spec[None][code][exc_class] = self.ensure_sync(f)709+ self.error_handler_spec[None][code][exc_class] = f710 711 @staticmethod712 def _get_exc_class_and_code(713 exc_class_or_code: t.Union[t.Type[Exception], int]19 unmodified lines733 return exc_class, exc_class.code734 else:735 return exc_class, None736 737- def ensure_sync(self, func: t.Callable) -> t.Callable:738- raise NotImplementedError()737 740-738 def _endpoint_from_view_func(view_func: t.Callable) -> str:739 """Internal helper that returns the default endpoint for a given740 function. This always is the function name.741 """121 unmodified linesmodified:tests/test_async.py+2 added-2 removed
4 unmodified lines5 6 from flask import Blueprint7 from flask import Flask8 from flask import request9-from flask.helpers import run_async9 10 pytest.importorskip("asgiref")11 12 121 unmodified lines134 135 136 @pytest.mark.skipif(sys.version_info >= (3, 7), reason="should only raise Python < 3.7")137 def test_async_runtime_error():138+ app = Flask(__name__)139 with pytest.raises(RuntimeError):140- run_async(None)140+ app.async_to_sync(None)