Skip to content
Myr

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.

authored by pgjones · committed by David Lord · parent cb13128 · Browse files · 6 files+53 added−68 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+53 added−68 removed

  • tests:+2 added−2 removed
  • other:+51 added−66 removed

6 files+53 added−68 removed

modified:docs/async-await.rst+15 added
90 unmodified lines
91not work with async views because they will not await the function or be92awaitable. Other functions they provide will not be awaitable either and93will probably be blocking if called within an async view.9495Extension authors can support async functions by utilising the96:meth:`flask.Flask.ensure_sync` method. For example, if the extension97provides a view function decorator add ``ensure_sync`` before calling98the decorated function,99100.. code-block:: python101102 def extension(func):103 @wraps(func)104 def wrapper(*args, **kwargs):105 ... # Extension logic106 return current_app.ensure_sync(func)(*args, **kwargs)107108 return wrapper109110Check the changelog of the extension you want to use to see if they've111implemented async support, or make a feature request or PR to them.112113
6 unmodified lines
modified:src/flask/app.py+14 added-16 removed
33 unmodified lines
34from .globals import _request_ctx_stack35from .globals import g36from .globals import request37from .globals import session38from .helpers import async_to_sync39from .helpers import get_debug_flag40from .helpers import get_env41from .helpers import get_flashed_messages42from .helpers import get_load_dotenv43from .helpers import locked_cached_property43from .helpers import run_async44from .helpers import url_for45from .json import jsonify46from .logging import create_logger47from .scaffold import _endpoint_from_view_func
1031 unmodified lines
10791080 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_func10891090 @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 lines
1205 value is ignored.12061207 .. versionadded:: 0.81208 """1211 self.before_first_request_funcs.append(self.ensure_sync(f))1209 self.before_first_request_funcs.append(f)1210 return f12111212 @setupmethod1213 def teardown_appcontext(self, f: TeardownCallable) -> TeardownCallable:
24 unmodified lines
1238 The return values of teardown functions are ignored.12391240 .. versionadded:: 0.91241 """1244 self.teardown_appcontext_funcs.append(self.ensure_sync(f))1242 self.teardown_appcontext_funcs.append(f)1243 return f12441245 @setupmethod1246 def shell_context_processor(self, f: t.Callable) -> t.Callable:
58 unmodified lines
13051306 handler = self._find_error_handler(e)1307 if handler is None:1308 return e1311 return handler(e)1309 return self.ensure_sync(handler)(e)13101311 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 request
58 unmodified lines
13721373 if handler is None:1374 raise13751378 return handler(e)1376 return self.ensure_sync(handler)(e)13771378 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 lines
1419 server_error = InternalServerError(original_exception=e)1420 handler = self._find_error_handler(server_error)14211422 if handler is not None:1425 server_error = handler(server_error)1423 server_error = self.ensure_sync(handler)(server_error)14241425 return self.finalize_request(server_error, from_error_handler=True)14261427 def log_exception(
53 unmodified lines
1481 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)14861487 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 and
52 unmodified lines
1542 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 = True15481549 def make_default_options_response(self) -> Response:1550 """This method is called to create the default ``OPTIONS`` response.
27 unmodified lines
15781579 .. versionadded:: 2.01580 """1581 if iscoroutinefunction(func):1584 return run_async(func)1582 return async_to_sync(func)15831584 return func15851586 def make_response(self, rv: ResponseReturnValue) -> Response:
217 unmodified lines
1804 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 rv18111812 return None
18 unmodified lines
1831 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 lines
1868 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)18741875 def do_teardown_appcontext(1876 self, exc: t.Optional[BaseException] = _sentinel # type: ignore
14 unmodified lines
1891 """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)18971898 def app_context(self) -> AppContext:1899 """Create an :class:`~flask.ctx.AppContext`. Use as a ``with``
146 unmodified lines
modified:src/flask/blueprints.py+8 added-32 removed
290 unmodified lines
291292 # Merge blueprint data into parent.293 if first_registration:294295 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}"298299 if ensure_sync:300 values = [app.ensure_sync(func) for func in values]301299 parent_dict[key].extend(values)300301 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] = value313314 for endpoint, func in self.view_functions.items():319 app.view_functions[endpoint] = app.ensure_sync(func)315 app.view_functions[endpoint] = func316317 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 lines
470 """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 f477478 def before_app_first_request(
1 unmodified line
480 ) -> 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 f486487 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 f495496 def teardown_app_request(self, f: TeardownCallable) -> TeardownCallable:
42 unmodified lines
539 self.record_once(540 lambda s: s.app.url_default_functions.setdefault(None, []).append(f)541 )542 return f556557 def ensure_sync(self, f: t.Callable) -> t.Callable:558 """Ensure the function is synchronous.559560 Override if you would like custom async to sync behaviour in561 this blueprint. Otherwise the app's562 :meth:`~flask.Flask.ensure_sync` is used.563564 .. versionadded:: 2.0565 """566 return f
modified:src/flask/helpers.py+9 added-10 removed
4 unmodified lines
5import typing as t6import warnings7from datetime import timedelta8from functools import update_wrapper9from functools import wraps9from threading import RLock1011import werkzeug.utils12from werkzeug.exceptions import NotFound
788 unmodified lines
801802 return False803804806def run_async(func: t.Callable[..., t.Coroutine]) -> t.Callable[..., t.Any]:807 """Return a sync function that will run the coroutine function *func*."""805def async_to_sync(func: t.Callable[..., t.Coroutine]) -> t.Callable[..., t.Any]:806 """Return a sync function that will run the coroutine function *func*.807808 This can be used as so809810 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 lines
821 raise RuntimeError(822 "Async cannot be used with this combination of Python & Greenlet versions."823 )824821 @wraps(func)822 def wrapper(*args: t.Any, **kwargs: t.Any) -> t.Any:823 return async_to_sync(func)(*args, **kwargs)824825 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 lines
520 function.521 """522523 def decorator(f):524 self.view_functions[endpoint] = self.ensure_sync(f)524 self.view_functions[endpoint] = f525 return f526527 return decorator528
15 unmodified lines
544 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 f550551 @setupmethod552 def after_request(self, f: AfterRequestCallable) -> AfterRequestCallable:
7 unmodified lines
560 ``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 f566567 @setupmethod568 def teardown_request(self, f: TeardownCallable) -> TeardownCallable:
30 unmodified lines
599 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 f605606 @setupmethod607 def context_processor(
97 unmodified lines
705 " code. Use a subclass of HTTPException with that code"706 " instead."707 )708709 self.error_handler_spec[None][code][exc_class] = self.ensure_sync(f)709 self.error_handler_spec[None][code][exc_class] = f710711 @staticmethod712 def _get_exc_class_and_code(713 exc_class_or_code: t.Union[t.Type[Exception], int]
19 unmodified lines
733 return exc_class, exc_class.code734 else:735 return exc_class, None736737 def ensure_sync(self, func: t.Callable) -> t.Callable:738 raise NotImplementedError()737740738def _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 lines
modified:tests/test_async.py+2 added-2 removed
4 unmodified lines
56from flask import Blueprint7from flask import Flask8from flask import request9from flask.helpers import run_async9from flask.helpers import async_to_sync1011pytest.importorskip("asgiref")1213
122 unmodified lines
136137@pytest.mark.skipif(sys.version_info >= (3, 7), reason="should only raise Python < 3.7")138def test_async_runtime_error():139 with pytest.raises(RuntimeError):140 run_async(None)140 async_to_sync(None)