Skip to content
Myr

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

5 files+169 added−32 removed

modified:src/flask/app.py+15 added
1import os2import sys3import weakref4from datetime import timedelta5from inspect import iscoroutinefunction6from itertools import chain7from threading import Lock89from werkzeug.datastructures import Headers
24 unmodified lines
34from .helpers import get_env35from .helpers import get_flashed_messages36from .helpers import get_load_dotenv37from .helpers import locked_cached_property38from .helpers import run_async39from .helpers import url_for40from .json import jsonify41from .logging import create_logger42from .scaffold import _endpoint_from_view_func
1475 unmodified lines
1518 .. versionadded:: 0.101519 """1520 return False15211522 def ensure_sync(self, func):1523 """Ensure that the returned function is sync and calls the async func.15241525 .. versionadded:: 2.015261527 Override if you wish to change how asynchronous functions are1528 run.1529 """1530 if iscoroutinefunction(func):1531 return run_async(func)15321533 return func15341535 def make_response(self, rv):1536 """Convert the return value from a view function to an instance of1537 :attr:`response_class`.1538
433 unmodified lines
modified:src/flask/blueprints.py+51 added-13 removed
1from collections import defaultdict2from functools import update_wrapper34from .scaffold import _endpoint_from_view_func5from .scaffold import _sentinel
229 unmodified lines
235236 # Merge blueprint data into parent.237 if first_registration:238238 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}"242243 if ensure_sync:244 values = [app.ensure_sync(func) for func in values]245246 parent_dict[key].extend(values)247243 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] = value261248 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)264265 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)277278 for deferred in self.deferred_functions:279 deferred(state)280
119 unmodified lines
400 """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 f409410 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 f418419 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 f429430 def teardown_app_request(self, f):
38 unmodified lines
469 self.record_once(470 lambda s: s.app.url_default_functions.setdefault(None, []).append(f)471 )472 return f473474 def ensure_sync(self, f):475 """Ensure the function is synchronous.476477 Override if you would like custom async to sync behaviour in478 this blueprint. Otherwise :meth:`~flask.Flask..ensure_sync` is479 used.480481 .. versionadded:: 2.0482 """483 return f
modified:src/flask/helpers.py+1 added
753 unmodified lines
754 This is similar to the copy_current_xxx_context functions in the755 ctx module, except it has an async inner.756 """757 ctx = None758759 if _request_ctx_stack.top is not None:760 ctx = _request_ctx_stack.top.copy()761762 @wraps(func)
17 unmodified lines
modified:src/flask/scaffold.py+1 added-13 removed
2 unmodified lines
3import pkgutil4import sys5from collections import defaultdict6from functools import update_wrapper7from inspect import iscoroutinefunction78from jinja2 import FileSystemLoader9from werkzeug.exceptions import default_exceptions10from werkzeug.exceptions import HTTPException1112from .cli import AppGroup13from .globals import current_app14from .helpers import locked_cached_property16from .helpers import run_async15from .helpers import send_from_directory16from .templating import _default_template_ctx_processor1718# a singleton sentinel value for parameter defaults
665 unmodified lines
684 else:685 return exc_class, None686687 def ensure_sync(self, func):690 """Ensure that the returned function is sync and calls the async func.688 raise NotImplementedError()689692 .. versionadded:: 2.0690694 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 func701702691def _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 lines
modified:tests/test_async.py+101 added-6 removed
1 unmodified line
2import sys34import pytest56from flask import abort6from flask import Blueprint7from flask import Flask8from flask import request9from flask.helpers import run_async101112class AppError(Exception):13 pass141516class BlueprintError(Exception):17 pass181920@pytest.fixture(name="async_app")21def _async_app():22 app = Flask(__name__)23
1 unmodified line
25 async def index():26 await asyncio.sleep(0)27 return request.method2829 @app.errorhandler(AppError)30 async def handle(_):31 return "", 4123233 @app.route("/error")34 async def error():23 abort(412)35 raise AppError()3637 blueprint = Blueprint("bp", __name__)3839 @blueprint.route("/", methods=["GET", "POST"])40 async def bp_index():41 await asyncio.sleep(0)42 return request.method4344 @blueprint.errorhandler(BlueprintError)45 async def bp_handle(_):46 return "", 4124748 @blueprint.route("/error")49 async def bp_error():50 raise BlueprintError()5152 app.register_blueprint(blueprint, url_prefix="/bp")5354 return app555657@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")58@pytest.mark.parametrize("path", ["/", "/bp/"])29def test_async_request_context(async_app):59def 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()656667@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")68@pytest.mark.parametrize("path", ["/error", "/bp/error"])69def 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 == 412737475@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")76def 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 = False8283 app = Flask(__name__)8485 @app.route("/")86 def index():87 return ""8889 @app.before_first_request90 async def before_first():91 nonlocal app_first_called92 app_first_called = True9394 @app.before_request95 async def before():96 nonlocal app_before_called97 app_before_called = True9899 @app.after_request100 async def after(response):101 nonlocal app_after_called102 app_after_called = True103 return response104105 blueprint = Blueprint("bp", __name__)106107 @blueprint.route("/")108 def bp_index():109 return ""110111 @blueprint.before_request112 async def bp_before():113 nonlocal bp_before_called114 bp_before_called = True115116 @blueprint.after_request117 async def bp_after(response):118 nonlocal bp_after_called119 bp_after_called = True120 return response121122 app.register_blueprint(blueprint, url_prefix="/bp")123124 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_called132133134@pytest.mark.skipif(sys.version_info >= (3, 7), reason="should only raise Python < 3.7")135def test_async_runtime_error():136 with pytest.raises(RuntimeError):137 run_async(None)