Alter ensure_sync implementation to support extensions

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.
This commit is contained in:
pgjones 2021-03-24 20:47:55 +00:00 committed by David Lord
parent c6c6408c3f
commit 00f5a3e55c
No known key found for this signature in database
GPG key ID: 7A1C87E3F5BC42A8
5 changed files with 169 additions and 32 deletions

View file

@ -2,6 +2,7 @@ import os
import sys
import weakref
from datetime import timedelta
from inspect import iscoroutinefunction
from itertools import chain
from threading import Lock
@ -34,6 +35,7 @@ from .helpers import get_env
from .helpers import get_flashed_messages
from .helpers import get_load_dotenv
from .helpers import locked_cached_property
from .helpers import run_async
from .helpers import url_for
from .json import jsonify
from .logging import create_logger
@ -1517,6 +1519,19 @@ class Flask(Scaffold):
"""
return False
def ensure_sync(self, func):
"""Ensure that the returned function is sync and calls the async func.
.. versionadded:: 2.0
Override if you wish to change how asynchronous functions are
run.
"""
if iscoroutinefunction(func):
return run_async(func)
return func
def make_response(self, rv):
"""Convert the return value from a view function to an instance of
:attr:`response_class`.