Simplify the async handling code
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Firstly `run_sync` was a misleading name as it didn't run anything, instead I think `async_to_sync` is much clearer as it converts a coroutine function to a function. (Name stolen from asgiref). Secondly trying to run the ensure_sync during registration made the code more complex and brittle, e.g. the _flask_async_wrapper usage. This was done to pay any setup costs during registration rather than runtime, however this only saved a iscoroutne check. It allows the weirdness of the Blueprint and Scaffold ensure_sync methods to be removed. Switching to runtime ensure_sync usage provides a method for extensions to also support async, as now documented.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+53 added−68 removed
- tests:+2 added−2 removed
- other:+51 added−66 removed
Provenance
- Commit
7f87f3d- Tree
9e5eaa1- Author
pgjones <philip.graham.jones@googlemail.com>- Committer
David Lord <davidism@gmail.com>- Parent
cb13128
6 files changed+53 added−68 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+14 added-16 removed
33 unmodified lines34 from .globals import _request_ctx_stack35 from .globals import g36 from .globals import request37 from .globals import session38+from .helpers import async_to_sync39 from .helpers import get_debug_flag40 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 async_to_sync(func)1583 1584 return func1585 1586 def make_response(self, rv: ResponseReturnValue) -> Response:217 unmodified lines1804 for bp in self._request_blueprints():1805 if bp in self.before_request_funcs:1806 funcs = chain(funcs, self.before_request_funcs[bp])1807 for func in funcs:1810- rv = func()1808+ rv = self.ensure_sync(func)()1809 if rv is not None:1810 return rv1811 1812 return None18 unmodified lines1831 funcs = chain(funcs, reversed(self.after_request_funcs[bp]))1832 if None in self.after_request_funcs:1833 funcs = chain(funcs, reversed(self.after_request_funcs[None]))1834 for handler in funcs:1837- response = handler(response)1835+ response = self.ensure_sync(handler)(response)1836 if not self.session_interface.is_null_session(ctx.session):1837 self.session_interface.save_session(self, ctx.session, response)1838 return response1839 28 unmodified lines1868 for bp in self._request_blueprints():1869 if bp in self.teardown_request_funcs:1870 funcs = chain(funcs, reversed(self.teardown_request_funcs[bp]))1871 for func in funcs:1874- func(exc)1872+ self.ensure_sync(func)(exc)1873 request_tearing_down.send(self, exc=exc)1874 1875 def do_teardown_appcontext(1876 self, exc: t.Optional[BaseException] = _sentinel # type: ignore14 unmodified lines1891 """1892 if exc is _sentinel:1893 exc = sys.exc_info()[1]1894 for func in reversed(self.teardown_appcontext_funcs):1897- func(exc)1895+ self.ensure_sync(func)(exc)1896 appcontext_tearing_down.send(self, exc=exc)1897 1898 def app_context(self) -> AppContext:1899 """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+9 added-10 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 NotFound788 unmodified lines801 802 return False803 804 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*."""805+def async_to_sync(func: t.Callable[..., t.Coroutine]) -> t.Callable[..., t.Any]:806+ """Return a sync function that will run the coroutine function *func*.807+808+ This can be used as so809+810+ result = async_to_async(func)(*args, **kwargs)811+ """812 try:809- from asgiref.sync import async_to_sync813+ from asgiref.sync import async_to_sync as asgiref_async_to_sync814 except ImportError:815 raise RuntimeError(816 "Install Flask with the 'async' extra in order to use async views."817 )3 unmodified lines821 raise RuntimeError(822 "Async cannot be used with this combination of Python & Greenlet versions."823 )824 821- @wraps(func)822- def wrapper(*args: t.Any, **kwargs: t.Any) -> t.Any:823- return async_to_sync(func)(*args, **kwargs)824-825- wrapper._flask_sync_wrapper = True # type: ignore826- return wrapper825+ return asgiref_async_to_sync(func)modified: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+from flask.helpers import async_to_sync10 11 pytest.importorskip("asgiref")12 13 122 unmodified lines136 137 @pytest.mark.skipif(sys.version_info >= (3, 7), reason="should only raise Python < 3.7")138 def test_async_runtime_error():139 with pytest.raises(RuntimeError):140- run_async(None)140+ async_to_sync(None)