Alter ensure_sync implementation to support extensions
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This allows extensions to override the Flask.ensure_sync method and have the change apply to blueprints as well. Without this change it is possible for differing blueprints to have differing ensure_sync approaches depending on the extension used - which would likely result in event-loop blocking issues. This also allows blueprints to have a custom ensure_sync, although this is a by product rather than an expected use case.
authored by pgjones · committed by David Lord · parent c6c6408 · Browse files · 5 files·+169 added−32 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+169 added−32 removed
- tests:+101 added−6 removed
- other:+68 added−26 removed
Provenance
- Commit
00f5a3e- Tree
555c74e- Author
pgjones <philip.graham.jones@googlemail.com>- Committer
David Lord <davidism@gmail.com>- Parent
c6c6408
5 files changed+169 added−32 removed
modified:src/flask/app.py+15 added
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_func1475 unmodified lines1518 .. versionadded:: 0.101519 """1520 return False1521 1522+ def ensure_sync(self, func):1523+ """Ensure that the returned function is sync and calls the async func.1524+1525+ .. versionadded:: 2.01526+1527+ Override if you wish to change how asynchronous functions are1528+ run.1529+ """1530+ if iscoroutinefunction(func):1531+ return run_async(func)1532+1533+ return func1534+1535 def make_response(self, rv):1536 """Convert the return value from a view function to an instance of1537 :attr:`response_class`.1538 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 :meth:`~flask.Flask..ensure_sync` is479+ used.480+481+ .. versionadded:: 2.0482+ """483+ return fmodified:src/flask/helpers.py+1 added
753 unmodified lines754 This is similar to the copy_current_xxx_context functions in the755 ctx module, except it has an async inner.756 """757 ctx = None758+759 if _request_ctx_stack.top is not None:760 ctx = _request_ctx_stack.top.copy()761 762 @wraps(func)17 unmodified linesmodified:src/flask/scaffold.py+1 added-13 removed
2 unmodified lines3 import pkgutil4 import sys5 from collections import defaultdict6 from functools import update_wrapper7-from inspect import iscoroutinefunction7 8 from jinja2 import FileSystemLoader9 from werkzeug.exceptions import default_exceptions10 from werkzeug.exceptions import HTTPException11 12 from .cli import AppGroup13 from .globals import current_app14 from .helpers import locked_cached_property16-from .helpers import run_async15 from .helpers import send_from_directory16 from .templating import _default_template_ctx_processor17 18 # a singleton sentinel value for parameter defaults665 unmodified lines684 else:685 return exc_class, None686 687 def ensure_sync(self, func):690- """Ensure that the returned function is sync and calls the async func.688+ raise NotImplementedError()689 692- .. versionadded:: 2.0690 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-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 linesmodified:tests/test_async.py+101 added-6 removed
1 unmodified line2 import sys3 4 import pytest5 6-from flask import abort6+from flask import Blueprint7 from flask import Flask8 from flask import request9 from flask.helpers import run_async10 11 12+class AppError(Exception):13+ pass14+15+16+class BlueprintError(Exception):17+ pass18+19+20 @pytest.fixture(name="async_app")21 def _async_app():22 app = Flask(__name__)23 1 unmodified line25 async def index():26 await asyncio.sleep(0)27 return request.method28 29+ @app.errorhandler(AppError)30+ async def handle(_):31+ return "", 41232+33 @app.route("/error")34 async def error():23- abort(412)35+ raise AppError()36 37+ blueprint = Blueprint("bp", __name__)38+39+ @blueprint.route("/", methods=["GET", "POST"])40+ async def bp_index():41+ await asyncio.sleep(0)42+ return request.method43+44+ @blueprint.errorhandler(BlueprintError)45+ async def bp_handle(_):46+ return "", 41247+48+ @blueprint.route("/error")49+ async def bp_error():50+ raise BlueprintError()51+52+ app.register_blueprint(blueprint, url_prefix="/bp")53+54 return app55 56 57 @pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")58+@pytest.mark.parametrize("path", ["/", "/bp/"])29-def test_async_request_context(async_app):59+def test_async_route(path, async_app):60 test_client = async_app.test_client()31- response = test_client.get("/")61+ response = test_client.get(path)62 assert b"GET" in response.get_data()33- response = test_client.post("/")63+ response = test_client.post(path)64 assert b"POST" in response.get_data()65+66+67+@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")68+@pytest.mark.parametrize("path", ["/error", "/bp/error"])69+def test_async_error_handler(path, async_app):70+ test_client = async_app.test_client()35- response = test_client.get("/error")71+ response = test_client.get(path)72 assert response.status_code == 41273 74 75+@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")76+def test_async_before_after_request():77+ app_first_called = False78+ app_before_called = False79+ app_after_called = False80+ bp_before_called = False81+ bp_after_called = False82+83+ app = Flask(__name__)84+85+ @app.route("/")86+ def index():87+ return ""88+89+ @app.before_first_request90+ async def before_first():91+ nonlocal app_first_called92+ app_first_called = True93+94+ @app.before_request95+ async def before():96+ nonlocal app_before_called97+ app_before_called = True98+99+ @app.after_request100+ async def after(response):101+ nonlocal app_after_called102+ app_after_called = True103+ return response104+105+ blueprint = Blueprint("bp", __name__)106+107+ @blueprint.route("/")108+ def bp_index():109+ return ""110+111+ @blueprint.before_request112+ async def bp_before():113+ nonlocal bp_before_called114+ bp_before_called = True115+116+ @blueprint.after_request117+ async def bp_after(response):118+ nonlocal bp_after_called119+ bp_after_called = True120+ return response121+122+ app.register_blueprint(blueprint, url_prefix="/bp")123+124+ test_client = app.test_client()125+ test_client.get("/")126+ assert app_first_called127+ assert app_before_called128+ assert app_after_called129+ test_client.get("/bp/")130+ assert bp_before_called131+ assert bp_after_called132+133+134 @pytest.mark.skipif(sys.version_info >= (3, 7), reason="should only raise Python < 3.7")135 def test_async_runtime_error():136 with pytest.raises(RuntimeError):137 run_async(None)