pass context through dispatch methods (#5818)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by GitHub · parents 88a65bb, 6a64969 · Browse files · 6 files·+167 added−72 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+167 added−72 removed
- tests:+6 added−5 removed
- other:+161 added−67 removed
Provenance
- Commit
70d04b5- Tree
b63807a- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
88a65bb- Parent 2
6a64969
6 files changed+167 added−72 removed
modified:src/flask/app.py+129 added-38 removed
1 from __future__ import annotations2 3 import collections.abc as cabc4+import inspect5 import os6 import sys7 import typing as t8 import weakref9 from datetime import timedelta10+from functools import update_wrapper11 from inspect import iscoroutinefunction12 from itertools import chain13 from types import TracebackType14 from urllib.parse import quote as _url_quote16 unmodified lines31 from . import cli32 from . import typing as ft33 from .ctx import AppContext34 from .globals import _cv_app35+from .globals import app_ctx36 from .globals import g37 from .globals import request38 from .globals import session39 from .helpers import get_debug_flag35 unmodified lines75 76 return timedelta(seconds=value)77 78 79+F = t.TypeVar("F", bound=t.Callable[..., t.Any])80+81+82+# Other methods may call the overridden method with the new ctx arg. Remove it83+# and call the method with the remaining args.84+def remove_ctx(f: F) -> F:85+ def wrapper(self: Flask, *args: t.Any, **kwargs: t.Any) -> t.Any:86+ if args and isinstance(args[0], AppContext):87+ args = args[1:]88+89+ return f(self, *args, **kwargs)90+91+ return update_wrapper(wrapper, f) # type: ignore[return-value]92+93+94+# The overridden method may call super().base_method without the new ctx arg.95+# Add it to the args for the call.96+def add_ctx(f: F) -> F:97+ def wrapper(self: Flask, *args: t.Any, **kwargs: t.Any) -> t.Any:98+ if not args:99+ args = (app_ctx._get_current_object(),)100+ elif not isinstance(args[0], AppContext):101+ args = (app_ctx._get_current_object(), *args)102+103+ return f(self, *args, **kwargs)104+105+ return update_wrapper(wrapper, f) # type: ignore[return-value]106+107+108 class Flask(App):109 """The flask object implements a WSGI application and acts as the central110 object. It is passed the name of the module or package of the111 application. Once it is created it will act as a central registry for137 unmodified lines249 #:250 #: .. versionadded:: 0.8251 session_interface: SessionInterface = SecureCookieSessionInterface()252 253+ def __init_subclass__(cls, **kwargs: t.Any) -> None:254+ import warnings255+256+ # These method signatures were updated to take a ctx param. Detect257+ # overridden methods in subclasses that still have the old signature.258+ # Show a deprecation warning and wrap to call with correct args.259+ for method in (260+ cls.handle_http_exception,261+ cls.handle_user_exception,262+ cls.handle_exception,263+ cls.log_exception,264+ cls.dispatch_request,265+ cls.full_dispatch_request,266+ cls.finalize_request,267+ cls.make_default_options_response,268+ cls.preprocess_request,269+ cls.process_response,270+ cls.do_teardown_request,271+ cls.do_teardown_appcontext,272+ ):273+ base_method = getattr(Flask, method.__name__)274+275+ if method is base_method:276+ # not overridden277+ continue278+279+ # get the second parameter (first is self)280+ iter_params = iter(inspect.signature(method).parameters.values())281+ next(iter_params)282+ param = next(iter_params, None)283+284+ # must have second parameter named ctx or annotated AppContext285+ if param is None or not (286+ # no annotation, match name287+ (param.annotation is inspect.Parameter.empty and param.name == "ctx")288+ or (289+ # string annotation, access path ends with AppContext290+ isinstance(param.annotation, str)291+ and param.annotation.rpartition(".")[2] == "AppContext"292+ )293+ or (294+ # class annotation295+ inspect.isclass(param.annotation)296+ and issubclass(param.annotation, AppContext)297+ )298+ ):299+ warnings.warn(300+ f"The '{method.__name__}' method now takes 'ctx: AppContext'"301+ " as the first parameter. The old signature is deprecated"302+ " and will not be supported in Flask 4.0.",303+ DeprecationWarning,304+ stacklevel=2,305+ )306+ setattr(cls, method.__name__, remove_ctx(method))307+ setattr(Flask, method.__name__, add_ctx(base_method))308+309 def __init__(310 self,311 import_name: str,312 static_url_path: str | None = None,272 unmodified lines585 from .debughelpers import FormDataRoutingRedirect586 587 raise FormDataRoutingRedirect(request)588 501- def update_template_context(self, context: dict[str, t.Any]) -> None:589+ def update_template_context(590+ self, ctx: AppContext, context: dict[str, t.Any]591+ ) -> None:592 """Update the template context with some commonly used variables.593 This injects request, session, config and g into the template594 context as well as everything template context processors want595 to inject. Note that the as of Flask 0.6, the original values5 unmodified lines601 """602 names: t.Iterable[str | None] = (None,)603 604 # A template may be rendered outside a request context.515- if (ctx := _cv_app.get(None)) is not None and ctx.has_request:605+ if ctx.has_request:606 names = chain(names, reversed(ctx.request.blueprints))607 608 # The values passed to render_template take precedence. Keep a609 # copy to re-apply after all context functions.216 unmodified lines826 827 return cls(self, **kwargs) # type: ignore828 829 def handle_http_exception(740- self, e: HTTPException830+ self, ctx: AppContext, e: HTTPException831 ) -> HTTPException | ft.ResponseReturnValue:832 """Handles an HTTP exception. By default this will invoke the833 registered error handlers and fall back to returning the834 exception as response.20 unmodified lines855 # are not raised or handled in user code.856 if isinstance(e, RoutingException):857 return e858 769- handler = self._find_error_handler(e, request.blueprints)859+ handler = self._find_error_handler(e, ctx.request.blueprints)860 if handler is None:861 return e862 return self.ensure_sync(handler)(e) # type: ignore[no-any-return]863 864 def handle_user_exception(775- self, e: Exception865+ self, ctx: AppContext, e: Exception866 ) -> HTTPException | ft.ResponseReturnValue:867 """This method is called whenever an exception occurs that868 should be handled. A special case is :class:`~werkzeug869 .exceptions.HTTPException` which is forwarded to the13 unmodified lines883 ):884 e.show_exception = True885 886 if isinstance(e, HTTPException) and not self.trap_http_exception(e):797- return self.handle_http_exception(e)887+ return self.handle_http_exception(ctx, e)888 799- handler = self._find_error_handler(e, request.blueprints)889+ handler = self._find_error_handler(e, ctx.request.blueprints)890 891 if handler is None:892 raise893 894 return self.ensure_sync(handler)(e) # type: ignore[no-any-return]895 806- def handle_exception(self, e: Exception) -> Response:896+ def handle_exception(self, ctx: AppContext, e: Exception) -> Response:897 """Handle an exception that did not have an error handler898 associated with it, or that was raised from an error handler.899 This always causes a 500 ``InternalServerError``.900 34 unmodified lines935 raise936 937 raise e938 849- self.log_exception(exc_info)939+ self.log_exception(ctx, exc_info)940 server_error: InternalServerError | ft.ResponseReturnValue941 server_error = InternalServerError(original_exception=e)852- handler = self._find_error_handler(server_error, request.blueprints)942+ handler = self._find_error_handler(server_error, ctx.request.blueprints)943 944 if handler is not None:945 server_error = self.ensure_sync(handler)(server_error)946 857- return self.finalize_request(server_error, from_error_handler=True)947+ return self.finalize_request(ctx, server_error, from_error_handler=True)948 949 def log_exception(950 self,861- exc_info: (tuple[type, BaseException, TracebackType] | tuple[None, None, None]),951+ ctx: AppContext,952+ exc_info: tuple[type, BaseException, TracebackType] | tuple[None, None, None],953 ) -> None:954 """Logs an exception. This is called by :meth:`handle_exception`955 if debugging is disabled and right before the handler is called.956 The default implementation logs the exception as error on the1 unmodified line958 959 .. versionadded:: 0.8960 """961 self.logger.error(871- f"Exception on {request.path} [{request.method}]", exc_info=exc_info962+ f"Exception on {ctx.request.path} [{ctx.request.method}]", exc_info=exc_info963 )964 874- def dispatch_request(self) -> ft.ResponseReturnValue:965+ def dispatch_request(self, ctx: AppContext) -> ft.ResponseReturnValue:966 """Does the request dispatching. Matches the URL and returns the967 return value of the view or error handler. This does not have to968 be a response object. In order to convert the return value to a969 proper response object, call :func:`make_response`.1 unmodified line971 .. versionchanged:: 0.7972 This no longer does the exception handling, this code was973 moved to the new :meth:`full_dispatch_request`.974 """884- req = _cv_app.get().request975+ req = ctx.request976 977 if req.routing_exception is not None:978 self.raise_routing_exception(req)979 rule: Rule = req.url_rule # type: ignore[assignment]2 unmodified lines982 if (983 getattr(rule, "provide_automatic_options", False)984 and req.method == "OPTIONS"985 ):895- return self.make_default_options_response()986+ return self.make_default_options_response(ctx)987 # otherwise dispatch to the handler for that endpoint988 view_args: dict[str, t.Any] = req.view_args # type: ignore[assignment]989 return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) # type: ignore[no-any-return]990 900- def full_dispatch_request(self) -> Response:991+ def full_dispatch_request(self, ctx: AppContext) -> Response:992 """Dispatches the request and on top of that performs request993 pre and postprocessing as well as HTTP exception catching and994 error handling.995 2 unmodified lines998 self._got_first_request = True999 1000 try:1001 request_started.send(self, _async_wrapper=self.ensure_sync)911- rv = self.preprocess_request()1002+ rv = self.preprocess_request(ctx)1003 if rv is None:913- rv = self.dispatch_request()1004+ rv = self.dispatch_request(ctx)1005 except Exception as e:915- rv = self.handle_user_exception(e)916- return self.finalize_request(rv)1006+ rv = self.handle_user_exception(ctx, e)1007+ return self.finalize_request(ctx, rv)1008 1009 def finalize_request(1010 self,1011+ ctx: AppContext,1012 rv: ft.ResponseReturnValue | HTTPException,1013 from_error_handler: bool = False,1014 ) -> Response:1015 """Given the return value from a view function this finalizes9 unmodified lines1025 :internal:1026 """1027 response = self.make_response(rv)1028 try:937- response = self.process_response(response)1029+ response = self.process_response(ctx, response)1030 request_finished.send(1031 self, _async_wrapper=self.ensure_sync, response=response1032 )1033 except Exception:3 unmodified lines1037 "Request finalizing failed with an error while handling an error"1038 )1039 return response1040 949- def make_default_options_response(self) -> Response:1041+ def make_default_options_response(self, ctx: AppContext) -> Response:1042 """This method is called to create the default ``OPTIONS`` response.1043 This can be changed through subclassing to change the default1044 behavior of ``OPTIONS`` responses.1045 1046 .. versionadded:: 0.71047 """956- adapter = _cv_app.get().url_adapter957- methods = adapter.allowed_methods() # type: ignore[union-attr]1048+ methods = ctx.url_adapter.allowed_methods() # type: ignore[union-attr]1049 rv = self.response_class()1050 rv.allow.update(methods)1051 return rv1052 297 unmodified lines1350 rv.headers.update(headers)1351 1352 return rv1353 1263- def preprocess_request(self) -> ft.ResponseReturnValue | None:1354+ def preprocess_request(self, ctx: AppContext) -> ft.ResponseReturnValue | None:1355 """Called before the request is dispatched. Calls1356 :attr:`url_value_preprocessors` registered with the app and the1357 current blueprint (if any). Then calls :attr:`before_request_funcs`1358 registered with the app and the blueprint.1 unmodified line1360 If any :meth:`before_request` handler returns a non-None value, the1361 value is handled as if it was the return value from the view, and1362 further request handling is stopped.1363 """1273- req = _cv_app.get().request1364+ req = ctx.request1365 names = (None, *reversed(req.blueprints))1366 1367 for name in names:1368 if name in self.url_value_preprocessors:9 unmodified lines1378 return rv # type: ignore[no-any-return]1379 1380 return None1381 1291- def process_response(self, response: Response) -> Response:1382+ def process_response(self, ctx: AppContext, response: Response) -> Response:1383 """Can be overridden in order to modify the response object1384 before it's sent to the WSGI server. By default this will1385 call all the :meth:`after_request` decorated functions.1386 4 unmodified lines1391 :param response: a :attr:`response_class` object.1392 :return: a new response object or the same, has to be an1393 instance of :attr:`response_class`.1394 """1304- ctx = _cv_app.get()1305-1395 for func in ctx._after_request_functions:1396 response = self.ensure_sync(func)(response)1397 1398 for name in chain(ctx.request.blueprints, (None,)):5 unmodified lines1404 self.session_interface.save_session(self, ctx.session, response)1405 1406 return response1407 1319- def do_teardown_request(self, exc: BaseException | None = None) -> None:1408+ def do_teardown_request(1409+ self, ctx: AppContext, exc: BaseException | None = None1410+ ) -> None:1411 """Called after the request is dispatched and the response is finalized,1412 right before the request context is popped. Called by1413 :meth:`.AppContext.pop`.1414 6 unmodified lines1421 1422 .. versionchanged:: 0.91423 Added the ``exc`` argument.1424 """1334- req = _cv_app.get().request1335-1336- for name in chain(req.blueprints, (None,)):1425+ for name in chain(ctx.request.blueprints, (None,)):1426 if name in self.teardown_request_funcs:1427 for func in reversed(self.teardown_request_funcs[name]):1428 self.ensure_sync(func)(exc)1429 1430 request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)1431 1343- def do_teardown_appcontext(self, exc: BaseException | None = None) -> None:1432+ def do_teardown_appcontext(1433+ self, ctx: AppContext, exc: BaseException | None = None1434+ ) -> None:1435 """Called right before the application context is popped. Called by1436 :meth:`.AppContext.pop`.1437 1438 This calls all functions decorated with :meth:`teardown_appcontext`.124 unmodified lines1563 error: BaseException | None = None1564 try:1565 try:1566 ctx.push()1476- response = self.full_dispatch_request()1567+ response = self.full_dispatch_request(ctx)1568 except Exception as e:1569 error = e1479- response = self.handle_exception(e)1570+ response = self.handle_exception(ctx, e)1571 except: # noqa: B0011572 error = sys.exc_info()[1]1573 raise1574 return response(environ, start_response)1575 finally:1576 if "werkzeug.debug.preserve_context" in environ:1486- environ["werkzeug.debug.preserve_context"](_cv_app.get())1577+ environ["werkzeug.debug.preserve_context"](ctx)1578 1579 if error is not None and self.should_ignore_error(error):1580 error = None1581 10 unmodified linesmodified:src/flask/ctx.py+2 added-2 removed
469 unmodified lines470 return471 472 try:473 if self._request is not None:474- self.app.do_teardown_request(exc)474+ self.app.do_teardown_request(self, exc)475 self._request.close()476 finally:477- self.app.do_teardown_appcontext(exc)477+ self.app.do_teardown_appcontext(self, exc)478 _cv_app.reset(self._cv_token)479 self._cv_token = None480 appcontext_popped.send(self.app, _async_wrapper=self.app.ensure_sync)481 35 unmodified linesmodified:src/flask/templating.py+25 added-27 removed
5 unmodified lines6 from jinja2 import Environment as BaseEnvironment7 from jinja2 import Template8 from jinja2 import TemplateNotFound9 10-from .globals import _cv_app11-from .globals import current_app10+from .ctx import AppContext11+from .globals import app_ctx12 from .helpers import stream_with_context13 from .signals import before_render_template14 from .signals import template_rendered15 16 if t.TYPE_CHECKING: # pragma: no cover17- from .app import Flask17 from .sansio.app import App18 from .sansio.scaffold import Scaffold19 20 21 def _default_template_ctx_processor() -> dict[str, t.Any]:22 """Default template context processor. Injects `request`,23 `session` and `g`.24 """26- ctx = _cv_app.get(None)27- rv: dict[str, t.Any] = {}25+ ctx = app_ctx._get_current_object()26+ rv: dict[str, t.Any] = {"g": ctx.g}27 29- if ctx is not None:30- rv["g"] = ctx.g28+ if ctx.has_request:29+ rv["request"] = ctx.request30+ rv["session"] = ctx.session31 32- if ctx.has_request:33- rv["request"] = ctx.request34- rv["session"] = ctx.session35-32 return rv33 34 35 class Environment(BaseEnvironment):82 unmodified lines118 119 return list(result)120 121 126-def _render(app: Flask, template: Template, context: dict[str, t.Any]) -> str:127- app.update_template_context(context)122+def _render(ctx: AppContext, template: Template, context: dict[str, t.Any]) -> str:123+ app = ctx.app124+ app.update_template_context(ctx, context)125 before_render_template.send(126 app, _async_wrapper=app.ensure_sync, template=template, context=context127 )128 rv = template.render(context)12 unmodified lines141 :param template_name_or_list: The name of the template to render. If142 a list is given, the first name to exist will be rendered.143 :param context: The variables to make available in the template.144 """148- app = current_app._get_current_object()149- template = app.jinja_env.get_or_select_template(template_name_or_list)150- return _render(app, template, context)145+ ctx = app_ctx._get_current_object()146+ template = ctx.app.jinja_env.get_or_select_template(template_name_or_list)147+ return _render(ctx, template, context)148 149 150 def render_template_string(source: str, **context: t.Any) -> str:151 """Render a template from the given source string with the given1 unmodified line153 154 :param source: The source code of the template to render.155 :param context: The variables to make available in the template.156 """160- app = current_app._get_current_object()161- template = app.jinja_env.from_string(source)162- return _render(app, template, context)157+ ctx = app_ctx._get_current_object()158+ template = ctx.app.jinja_env.from_string(source)159+ return _render(ctx, template, context)160 161 162 def _stream(166- app: Flask, template: Template, context: dict[str, t.Any]163+ ctx: AppContext, template: Template, context: dict[str, t.Any]164 ) -> t.Iterator[str]:165+ app = ctx.app168- app.update_template_context(context)166+ app.update_template_context(ctx, context)167 before_render_template.send(168 app, _async_wrapper=app.ensure_sync, template=template, context=context169 )170 19 unmodified lines190 :param context: The variables to make available in the template.191 192 .. versionadded:: 2.2193 """196- app = current_app._get_current_object()197- template = app.jinja_env.get_or_select_template(template_name_or_list)198- return _stream(app, template, context)194+ ctx = app_ctx._get_current_object()195+ template = ctx.app.jinja_env.get_or_select_template(template_name_or_list)196+ return _stream(ctx, template, context)197 198 199 def stream_template_string(source: str, **context: t.Any) -> t.Iterator[str]:200 """Render a template from the given source string with the given4 unmodified lines205 :param context: The variables to make available in the template.206 207 .. versionadded:: 2.2208 """211- app = current_app._get_current_object()212- template = app.jinja_env.from_string(source)213- return _stream(app, template, context)209+ ctx = app_ctx._get_current_object()210+ template = ctx.app.jinja_env.from_string(source)211+ return _stream(ctx, template, context)modified:tests/test_reqctx.py+5 added-4 removed
286 unmodified lines287 288 # use a non-printable character in the Host - this is key to this test289 environ["HTTP_HOST"] = "\x8a"290 291- with app.request_context(environ):292- response = app.full_dispatch_request()291+ with app.request_context(environ) as ctx:292+ response = app.full_dispatch_request(ctx)293+294 assert response.status_code == 400295 296 297 def test_environ_for_valid_idna_completes():10 unmodified lines308 309 # these characters are all IDNA-compatible310 environ["HTTP_HOST"] = "ąśźäüжŠßя.com"311 311- with app.request_context(environ):312- response = app.full_dispatch_request()312+ with app.request_context(environ) as ctx:313+ response = app.full_dispatch_request(ctx)314 315 assert response.status_code == 200316 317 9 unmodified linesmodified:tests/test_subclassing.py+1 added-1 removed
3 unmodified lines4 5 6 def test_suppressed_exception_logging():7 class SuppressedFlask(flask.Flask):8- def log_exception(self, exc_info):8+ def log_exception(self, ctx, exc_info):9 pass10 11 out = StringIO()12 app = SuppressedFlask(__name__)9 unmodified linesmodified:CHANGES.rst+5 added
7 unmodified lines8 - ``RequestContext`` has merged with ``AppContext``. ``RequestContext`` is now9 a deprecated alias. If an app context is already pushed, it is not reused10 when dispatching a request. This greatly simplifies the internal code for tracking11 the active context. :issue:`5639`12+- Many ``Flask`` methods involved in request dispatch now take the current13+ ``AppContext`` as the first parameter, instead of using the proxy objects.14+ If subclasses were overriding these methods, the old signature is detected,15+ shows a deprecation warning, and will continue to work during the16+ deprecation period. :issue:`5815`17 - ``template_filter``, ``template_test``, and ``template_global`` decorators18 can be used without parentheses. :issue:`5729`19 20 1624 unmodified lines