Skip to content
Myr

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

6 files+167 added−72 removed

modified:src/flask/app.py+129 added-38 removed
1from __future__ import annotations23import collections.abc as cabc4import inspect5import os6import sys7import typing as t8import weakref9from datetime import timedelta10from functools import update_wrapper11from inspect import iscoroutinefunction12from itertools import chain13from types import TracebackType14from urllib.parse import quote as _url_quote
16 unmodified lines
31from . import cli32from . import typing as ft33from .ctx import AppContext34from .globals import _cv_app35from .globals import app_ctx36from .globals import g37from .globals import request38from .globals import session39from .helpers import get_debug_flag
35 unmodified lines
7576 return timedelta(seconds=value)777879F = t.TypeVar("F", bound=t.Callable[..., t.Any])808182# Other methods may call the overridden method with the new ctx arg. Remove it83# and call the method with the remaining args.84def 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:]8889 return f(self, *args, **kwargs)9091 return update_wrapper(wrapper, f) # type: ignore[return-value]929394# The overridden method may call super().base_method without the new ctx arg.95# Add it to the args for the call.96def 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)102103 return f(self, *args, **kwargs)104105 return update_wrapper(wrapper, f) # type: ignore[return-value]106107108class 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 for
137 unmodified lines
249 #:250 #: .. versionadded:: 0.8251 session_interface: SessionInterface = SecureCookieSessionInterface()252253 def __init_subclass__(cls, **kwargs: t.Any) -> None:254 import warnings255256 # 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__)274275 if method is base_method:276 # not overridden277 continue278279 # 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)283284 # 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))308309 def __init__(310 self,311 import_name: str,312 static_url_path: str | None = None,
272 unmodified lines
585 from .debughelpers import FormDataRoutingRedirect586587 raise FormDataRoutingRedirect(request)588501 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 values
5 unmodified lines
601 """602 names: t.Iterable[str | None] = (None,)603604 # 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))607608 # The values passed to render_template take precedence. Keep a609 # copy to re-apply after all context functions.
216 unmodified lines
826827 return cls(self, **kwargs) # type: ignore828829 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 lines
855 # are not raised or handled in user code.856 if isinstance(e, RoutingException):857 return e858769 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]863864 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 the
13 unmodified lines
883 ):884 e.show_exception = True885886 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)888799 handler = self._find_error_handler(e, request.blueprints)889 handler = self._find_error_handler(e, ctx.request.blueprints)890891 if handler is None:892 raise893894 return self.ensure_sync(handler)(e) # type: ignore[no-any-return]895806 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 lines
935 raise936937 raise e938849 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)943944 if handler is not None:945 server_error = self.ensure_sync(handler)(server_error)946857 return self.finalize_request(server_error, from_error_handler=True)947 return self.finalize_request(ctx, server_error, from_error_handler=True)948949 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 the
1 unmodified line
958959 .. 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 )964874 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 line
971 .. 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.request976977 if req.routing_exception is not None:978 self.raise_routing_exception(req)979 rule: Rule = req.url_rule # type: ignore[assignment]
2 unmodified lines
982 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]990900 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 lines
998 self._got_first_request = True9991000 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)10081009 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 finalizes
9 unmodified lines
1025 :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 lines
1037 "Request finalizing failed with an error while handling an error"1038 )1039 return response1040949 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.10451046 .. 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 lines
1350 rv.headers.update(headers)13511352 return rv13531263 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 line
1360 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))13661367 for name in names:1368 if name in self.url_value_preprocessors:
9 unmodified lines
1378 return rv # type: ignore[no-any-return]13791380 return None13811291 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 lines
1391 :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()13051395 for func in ctx._after_request_functions:1396 response = self.ensure_sync(func)(response)13971398 for name in chain(ctx.request.blueprints, (None,)):
5 unmodified lines
1404 self.session_interface.save_session(self, ctx.session, response)14051406 return response14071319 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 lines
14211422 .. versionchanged:: 0.91423 Added the ``exc`` argument.1424 """1334 req = _cv_app.get().request13351336 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)14291430 request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)14311343 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`.14371438 This calls all functions decorated with :meth:`teardown_appcontext`.
124 unmodified lines
1563 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)15781579 if error is not None and self.should_ignore_error(error):1580 error = None1581
10 unmodified lines
modified:src/flask/ctx.py+2 added-2 removed
469 unmodified lines
470 return471472 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 lines
modified:src/flask/templating.py+25 added-27 removed
5 unmodified lines
6from jinja2 import Environment as BaseEnvironment7from jinja2 import Template8from jinja2 import TemplateNotFound910from .globals import _cv_app11from .globals import current_app10from .ctx import AppContext11from .globals import app_ctx12from .helpers import stream_with_context13from .signals import before_render_template14from .signals import template_rendered1516if t.TYPE_CHECKING: # pragma: no cover17 from .app import Flask17 from .sansio.app import App18 from .sansio.scaffold import Scaffold192021def _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}2729 if ctx is not None:30 rv["g"] = ctx.g28 if ctx.has_request:29 rv["request"] = ctx.request30 rv["session"] = ctx.session3132 if ctx.has_request:33 rv["request"] = ctx.request34 rv["session"] = ctx.session3532 return rv333435class Environment(BaseEnvironment):
82 unmodified lines
118119 return list(result)120121126def _render(app: Flask, template: Template, context: dict[str, t.Any]) -> str:127 app.update_template_context(context)122def _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 lines
141 :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)148149150def render_template_string(source: str, **context: t.Any) -> str:151 """Render a template from the given source string with the given
1 unmodified line
153154 :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)160161162def _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 lines
190 :param context: The variables to make available in the template.191192 .. 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)197198199def stream_template_string(source: str, **context: t.Any) -> t.Iterator[str]:200 """Render a template from the given source string with the given
4 unmodified lines
205 :param context: The variables to make available in the template.206207 .. 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 lines
287288 # use a non-printable character in the Host - this is key to this test289 environ["HTTP_HOST"] = "\x8a"290291 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)293294 assert response.status_code == 400295296297def test_environ_for_valid_idna_completes():
10 unmodified lines
308309 # these characters are all IDNA-compatible310 environ["HTTP_HOST"] = "ąśźäüжŠßя.com"311311 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)314315 assert response.status_code == 200316317
9 unmodified lines
modified:tests/test_subclassing.py+1 added-1 removed
3 unmodified lines
456def 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 pass1011 out = StringIO()12 app = SuppressedFlask(__name__)
9 unmodified lines
modified:CHANGES.rst+5 added
7 unmodified lines
8- ``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`1920
1624 unmodified lines