Skip to content
Myr

Merge pull request #4603 from f3ndot/use-correct-response-type-for-after-request-callable

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Fix type annotation for `after_request` callable type

authored by David Lord · committed by GitHub · parents a4f63e0, 61f62e6 · Browse files · 7 files+85 added−98 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+85 added−98 removed

  • other:+85 added−98 removed

7 files+85 added−98 removed

modified:src/flask/app.py+26 added-30 removed
24 unmodified lines
25from werkzeug.wrappers import Response as BaseResponse2627from . import cli28from . import json29from . import typing as ft30from .config import Config31from .config import ConfigAttribute32from .ctx import _AppCtxGlobals33from .ctx import AppContext
24 unmodified lines
58from .signals import request_started59from .signals import request_tearing_down60from .templating import DispatchingJinjaLoader61from .templating import Environment61from .typing import BeforeFirstRequestCallable62from .typing import ResponseReturnValue63from .typing import TeardownCallable64from .typing import TemplateFilterCallable65from .typing import TemplateGlobalCallable66from .typing import TemplateTestCallable62from .wrappers import Request63from .wrappers import Response6465if t.TYPE_CHECKING:66 import typing_extensions as te67 from .blueprints import Blueprint68 from .testing import FlaskClient69 from .testing import FlaskCliRunner75 from .typing import ErrorHandlerCallable7071if sys.version_info >= (3, 8):72 iscoroutinefunction = inspect.iscoroutinefunction73else:
355 unmodified lines
429 #: first request to this instance. To register a function, use the430 #: :meth:`before_first_request` decorator.431 #:432 #: .. versionadded:: 0.8439 self.before_first_request_funcs: t.List[BeforeFirstRequestCallable] = []433 self.before_first_request_funcs: t.List[ft.BeforeFirstRequestCallable] = []434435 #: A list of functions that are called when the application context436 #: is destroyed. Since the application context is also torn down437 #: if the request ends this is the place to store code that disconnects438 #: from databases.439 #:440 #: .. versionadded:: 0.9447 self.teardown_appcontext_funcs: t.List[TeardownCallable] = []441 self.teardown_appcontext_funcs: t.List[ft.TeardownCallable] = []442443 #: A list of shell context processor functions that should be run444 #: when a shell context is created.445 #:
643 unmodified lines
10891090 @setupmethod1091 def template_filter(1092 self, name: t.Optional[str] = None1099 ) -> t.Callable[[TemplateFilterCallable], TemplateFilterCallable]:1093 ) -> t.Callable[[ft.TemplateFilterCallable], ft.TemplateFilterCallable]:1094 """A decorator that is used to register custom template filter.1095 You can specify a name for the filter, otherwise the function1096 name will be used. Example::1097
4 unmodified lines
1102 :param name: the optional name of the filter, otherwise the1103 function name will be used.1104 """11051112 def decorator(f: TemplateFilterCallable) -> TemplateFilterCallable:1106 def decorator(f: ft.TemplateFilterCallable) -> ft.TemplateFilterCallable:1107 self.add_template_filter(f, name=name)1108 return f11091110 return decorator11111112 @setupmethod1113 def add_template_filter(1120 self, f: TemplateFilterCallable, name: t.Optional[str] = None1114 self, f: ft.TemplateFilterCallable, name: t.Optional[str] = None1115 ) -> None:1116 """Register a custom template filter. Works exactly like the1117 :meth:`template_filter` decorator.1118
4 unmodified lines
11231124 @setupmethod1125 def template_test(1126 self, name: t.Optional[str] = None1133 ) -> t.Callable[[TemplateTestCallable], TemplateTestCallable]:1127 ) -> t.Callable[[ft.TemplateTestCallable], ft.TemplateTestCallable]:1128 """A decorator that is used to register custom template test.1129 You can specify a name for the test, otherwise the function1130 name will be used. Example::1131
11 unmodified lines
1143 :param name: the optional name of the test, otherwise the1144 function name will be used.1145 """11461153 def decorator(f: TemplateTestCallable) -> TemplateTestCallable:1147 def decorator(f: ft.TemplateTestCallable) -> ft.TemplateTestCallable:1148 self.add_template_test(f, name=name)1149 return f11501151 return decorator11521153 @setupmethod1154 def add_template_test(1161 self, f: TemplateTestCallable, name: t.Optional[str] = None1155 self, f: ft.TemplateTestCallable, name: t.Optional[str] = None1156 ) -> None:1157 """Register a custom template test. Works exactly like the1158 :meth:`template_test` decorator.1159
6 unmodified lines
11661167 @setupmethod1168 def template_global(1169 self, name: t.Optional[str] = None1176 ) -> t.Callable[[TemplateGlobalCallable], TemplateGlobalCallable]:1170 ) -> t.Callable[[ft.TemplateGlobalCallable], ft.TemplateGlobalCallable]:1171 """A decorator that is used to register a custom template global function.1172 You can specify a name for the global function, otherwise the function1173 name will be used. Example::1174
6 unmodified lines
1181 :param name: the optional name of the global function, otherwise the1182 function name will be used.1183 """11841191 def decorator(f: TemplateGlobalCallable) -> TemplateGlobalCallable:1185 def decorator(f: ft.TemplateGlobalCallable) -> ft.TemplateGlobalCallable:1186 self.add_template_global(f, name=name)1187 return f11881189 return decorator11901191 @setupmethod1192 def add_template_global(1199 self, f: TemplateGlobalCallable, name: t.Optional[str] = None1193 self, f: ft.TemplateGlobalCallable, name: t.Optional[str] = None1194 ) -> None:1195 """Register a custom template global function. Works exactly like the1196 :meth:`template_global` decorator.1197
5 unmodified lines
1203 self.jinja_env.globals[name or f.__name__] = f12041205 @setupmethod1206 def before_first_request(1213 self, f: BeforeFirstRequestCallable1214 ) -> BeforeFirstRequestCallable:1207 self, f: ft.BeforeFirstRequestCallable1208 ) -> ft.BeforeFirstRequestCallable:1209 """Registers a function to be run before the first request to this1210 instance of the application.12111212 The function will be called without any arguments and its return
4 unmodified lines
1217 self.before_first_request_funcs.append(f)1218 return f12191220 @setupmethod1227 def teardown_appcontext(self, f: TeardownCallable) -> TeardownCallable:1221 def teardown_appcontext(self, f: ft.TeardownCallable) -> ft.TeardownCallable:1222 """Registers a function to be called when the application context1223 ends. These functions are typically also called when the request1224 context is popped.1225
32 unmodified lines
1258 """1259 self.shell_context_processors.append(f)1260 return f12611268 def _find_error_handler(self, e: Exception) -> t.Optional["ErrorHandlerCallable"]:1262 def _find_error_handler(self, e: Exception) -> t.Optional[ft.ErrorHandlerCallable]:1263 """Return a registered error handler for an exception in this order:1264 blueprint handler for a specific code, app handler for a specific code,1265 blueprint handler for an exception class, app handler for an exception1266 class, or ``None`` if a suitable handler is not found.
16 unmodified lines
1283 return None12841285 def handle_http_exception(1286 self, e: HTTPException1293 ) -> t.Union[HTTPException, ResponseReturnValue]:1287 ) -> t.Union[HTTPException, ft.ResponseReturnValue]:1288 """Handles an HTTP exception. By default this will invoke the1289 registered error handlers and fall back to returning the1290 exception as response.1291
61 unmodified lines
1353 return False13541355 def handle_user_exception(1356 self, e: Exception1363 ) -> t.Union[HTTPException, ResponseReturnValue]:1357 ) -> t.Union[HTTPException, ft.ResponseReturnValue]:1358 """This method is called whenever an exception occurs that1359 should be handled. A special case is :class:`~werkzeug1360 .exceptions.HTTPException` which is forwarded to the1361 :meth:`handle_http_exception` method. This function will either
61 unmodified lines
14231424 raise e14251426 self.log_exception(exc_info)1433 server_error: t.Union[InternalServerError, ResponseReturnValue]1427 server_error: t.Union[InternalServerError, ft.ResponseReturnValue]1428 server_error = InternalServerError(original_exception=e)1429 handler = self._find_error_handler(server_error)14301431 if handler is not None:
45 unmodified lines
1477 from .debughelpers import FormDataRoutingRedirect14781479 raise FormDataRoutingRedirect(request)14801487 def dispatch_request(self) -> ResponseReturnValue:1481 def dispatch_request(self) -> ft.ResponseReturnValue:1482 """Does the request dispatching. Matches the URL and returns the1483 return value of the view or error handler. This does not have to1484 be a response object. In order to convert the return value to a1485 proper response object, call :func:`make_response`.
34 unmodified lines
1520 return self.finalize_request(rv)15211522 def finalize_request(1523 self,1530 rv: t.Union[ResponseReturnValue, HTTPException],1524 rv: t.Union[ft.ResponseReturnValue, HTTPException],1525 from_error_handler: bool = False,1526 ) -> Response:1527 """Given the return value from a view function this finalizes1528 the request by converting it into a response and invoking the
94 unmodified lines
1623 ) from None16241625 return asgiref_async_to_sync(func)16261633 def make_response(self, rv: ResponseReturnValue) -> Response:1627 def make_response(self, rv: ft.ResponseReturnValue) -> Response:1628 """Convert the return value from a view function to an instance of1629 :attr:`response_class`.16301631 :param rv: the return value from the view function. The view function
83 unmodified lines
1715 elif isinstance(rv, BaseResponse) or callable(rv):1716 # evaluate a WSGI callable, or coerce a different response1717 # class to the correct type1718 try:1725 rv = self.response_class.force_type(rv, request.environ) # type: ignore # noqa: B9501719 rv = self.response_class.force_type(1720 rv, request.environ # type: ignore[arg-type]1721 )1722 except TypeError as e:1723 raise TypeError(1724 f"{e}\nThe view function did not return a valid"1725 " response. The return type must be a string,"
107 unmodified lines
1833 raise18341835 raise error18361841 def preprocess_request(self) -> t.Optional[ResponseReturnValue]:1837 def preprocess_request(self) -> t.Optional[ft.ResponseReturnValue]:1838 """Called before the request is dispatched. Calls1839 :attr:`url_value_preprocessors` registered with the app and the1840 current blueprint (if any). Then calls :attr:`before_request_funcs`1841 registered with the app and the blueprint.
250 unmodified lines
modified:src/flask/blueprints.py+23 added-31 removed
1 unmodified line
2import typing as t3from collections import defaultdict4from functools import update_wrapper56from . import typing as ft7from .scaffold import _endpoint_from_view_func8from .scaffold import _sentinel9from .scaffold import Scaffold9from .typing import AfterRequestCallable10from .typing import BeforeFirstRequestCallable11from .typing import BeforeRequestCallable12from .typing import TeardownCallable13from .typing import TemplateContextProcessorCallable14from .typing import TemplateFilterCallable15from .typing import TemplateGlobalCallable16from .typing import TemplateTestCallable17from .typing import URLDefaultCallable18from .typing import URLValuePreprocessorCallable1011if t.TYPE_CHECKING:12 from .app import Flask22 from .typing import ErrorHandlerCallable1314DeferredSetupFunction = t.Callable[["BlueprintSetupState"], t.Callable]1516
391 unmodified lines
408 )409410 def app_template_filter(411 self, name: t.Optional[str] = None422 ) -> t.Callable[[TemplateFilterCallable], TemplateFilterCallable]:412 ) -> t.Callable[[ft.TemplateFilterCallable], ft.TemplateFilterCallable]:413 """Register a custom template filter, available application wide. Like414 :meth:`Flask.template_filter` but for a blueprint.415416 :param name: the optional name of the filter, otherwise the417 function name will be used.418 """419430 def decorator(f: TemplateFilterCallable) -> TemplateFilterCallable:420 def decorator(f: ft.TemplateFilterCallable) -> ft.TemplateFilterCallable:421 self.add_app_template_filter(f, name=name)422 return f423424 return decorator425426 def add_app_template_filter(437 self, f: TemplateFilterCallable, name: t.Optional[str] = None427 self, f: ft.TemplateFilterCallable, name: t.Optional[str] = None428 ) -> None:429 """Register a custom template filter, available application wide. Like430 :meth:`Flask.add_template_filter` but for a blueprint. Works exactly431 like the :meth:`app_template_filter` decorator.
8 unmodified lines
440 self.record_once(register_template)441442 def app_template_test(443 self, name: t.Optional[str] = None454 ) -> t.Callable[[TemplateTestCallable], TemplateTestCallable]:444 ) -> t.Callable[[ft.TemplateTestCallable], ft.TemplateTestCallable]:445 """Register a custom template test, available application wide. Like446 :meth:`Flask.template_test` but for a blueprint.447448 .. versionadded:: 0.10
1 unmodified line
450 :param name: the optional name of the test, otherwise the451 function name will be used.452 """453464 def decorator(f: TemplateTestCallable) -> TemplateTestCallable:454 def decorator(f: ft.TemplateTestCallable) -> ft.TemplateTestCallable:455 self.add_app_template_test(f, name=name)456 return f457458 return decorator459460 def add_app_template_test(471 self, f: TemplateTestCallable, name: t.Optional[str] = None461 self, f: ft.TemplateTestCallable, name: t.Optional[str] = None462 ) -> None:463 """Register a custom template test, available application wide. Like464 :meth:`Flask.add_template_test` but for a blueprint. Works exactly465 like the :meth:`app_template_test` decorator.
10 unmodified lines
476 self.record_once(register_template)477478 def app_template_global(479 self, name: t.Optional[str] = None490 ) -> t.Callable[[TemplateGlobalCallable], TemplateGlobalCallable]:480 ) -> t.Callable[[ft.TemplateGlobalCallable], ft.TemplateGlobalCallable]:481 """Register a custom template global, available application wide. Like482 :meth:`Flask.template_global` but for a blueprint.483484 .. versionadded:: 0.10
1 unmodified line
486 :param name: the optional name of the global, otherwise the487 function name will be used.488 """489500 def decorator(f: TemplateGlobalCallable) -> TemplateGlobalCallable:490 def decorator(f: ft.TemplateGlobalCallable) -> ft.TemplateGlobalCallable:491 self.add_app_template_global(f, name=name)492 return f493494 return decorator495496 def add_app_template_global(507 self, f: TemplateGlobalCallable, name: t.Optional[str] = None497 self, f: ft.TemplateGlobalCallable, name: t.Optional[str] = None498 ) -> None:499 """Register a custom template global, available application wide. Like500 :meth:`Flask.add_template_global` but for a blueprint. Works exactly501 like the :meth:`app_template_global` decorator.
8 unmodified lines
510 state.app.jinja_env.globals[name or f.__name__] = f511512 self.record_once(register_template)513524 def before_app_request(self, f: BeforeRequestCallable) -> BeforeRequestCallable:514 def before_app_request(515 self, f: ft.BeforeRequestCallable516 ) -> ft.BeforeRequestCallable:517 """Like :meth:`Flask.before_request`. Such a function is executed518 before each request, even if outside of a blueprint.519 """520 self.record_once(
1 unmodified line
522 )523 return f524525 def before_app_first_request(534 self, f: BeforeFirstRequestCallable535 ) -> BeforeFirstRequestCallable:526 self, f: ft.BeforeFirstRequestCallable527 ) -> ft.BeforeFirstRequestCallable:528 """Like :meth:`Flask.before_first_request`. Such a function is529 executed before the first request to the application.530 """531 self.record_once(lambda s: s.app.before_first_request_funcs.append(f))532 return f533542 def after_app_request(self, f: AfterRequestCallable) -> AfterRequestCallable:534 def after_app_request(self, f: ft.AfterRequestCallable) -> ft.AfterRequestCallable:535 """Like :meth:`Flask.after_request` but for a blueprint. Such a function536 is executed after each request, even if outside of the blueprint.537 """538 self.record_once(539 lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)540 )541 return f542551 def teardown_app_request(self, f: TeardownCallable) -> TeardownCallable:543 def teardown_app_request(self, f: ft.TeardownCallable) -> ft.TeardownCallable:544 """Like :meth:`Flask.teardown_request` but for a blueprint. Such a545 function is executed when tearing down each request, even if outside of546 the blueprint.547 """
2 unmodified lines
550 )551 return f552553 def app_context_processor(562 self, f: TemplateContextProcessorCallable563 ) -> TemplateContextProcessorCallable:554 self, f: ft.TemplateContextProcessorCallable555 ) -> ft.TemplateContextProcessorCallable:556 """Like :meth:`Flask.context_processor` but for a blueprint. Such a557 function is executed each request, even if outside of the blueprint.558 """559 self.record_once(
5 unmodified lines
565 """Like :meth:`Flask.errorhandler` but for a blueprint. This566 handler is used for all requests, even if outside of the blueprint.567 """568577 def decorator(f: "ErrorHandlerCallable") -> "ErrorHandlerCallable":569 def decorator(f: ft.ErrorHandlerCallable) -> ft.ErrorHandlerCallable:570 self.record_once(lambda s: s.app.errorhandler(code)(f))571 return f572573 return decorator574575 def app_url_value_preprocessor(584 self, f: URLValuePreprocessorCallable585 ) -> URLValuePreprocessorCallable:576 self, f: ft.URLValuePreprocessorCallable577 ) -> ft.URLValuePreprocessorCallable:578 """Same as :meth:`url_value_preprocessor` but application wide."""579 self.record_once(580 lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)581 )582 return f583592 def app_url_defaults(self, f: URLDefaultCallable) -> URLDefaultCallable:584 def app_url_defaults(self, f: ft.URLDefaultCallable) -> ft.URLDefaultCallable:585 """Same as :meth:`url_defaults` but application wide."""586 self.record_once(587 lambda s: s.app.url_default_functions.setdefault(None, []).append(f)588 )
1 unmodified line
modified:src/flask/ctx.py+3 added-3 removed
3 unmodified lines
4from types import TracebackType56from werkzeug.exceptions import HTTPException78from . import typing as ft9from .globals import _app_ctx_stack10from .globals import _request_ctx_stack11from .signals import appcontext_popped12from .signals import appcontext_pushed12from .typing import AfterRequestCallable1314if t.TYPE_CHECKING:15 from .app import Flask16 from .sessions import SessionMixin
91 unmodified lines
108 return f"<flask.g of {top.app.name!r}>"109 return object.__repr__(self)110111112def after_this_request(f: AfterRequestCallable) -> AfterRequestCallable:112def after_this_request(f: ft.AfterRequestCallable) -> ft.AfterRequestCallable:113 """Executes a function after this request. This is useful to modify114 response objects. The function is passed the response object and has115 to return the same or a new one.116
223 unmodified lines
340341 # Functions that should be executed after the request on the response342 # object. These will be called before the regular "after_request"343 # functions.344 self._after_request_functions: t.List[AfterRequestCallable] = []344 self._after_request_functions: t.List[ft.AfterRequestCallable] = []345346 @property347 def g(self) -> _AppCtxGlobals:348 import warnings
165 unmodified lines
modified:src/flask/scaffold.py+21 added-28 removed
10 unmodified lines
11from jinja2 import FileSystemLoader12from werkzeug.exceptions import default_exceptions13from werkzeug.exceptions import HTTPException1415from . import typing as ft16from .cli import AppGroup17from .globals import current_app18from .helpers import get_root_path19from .helpers import locked_cached_property20from .helpers import send_from_directory21from .templating import _default_template_ctx_processor21from .typing import AfterRequestCallable22from .typing import AppOrBlueprintKey23from .typing import BeforeRequestCallable24from .typing import TeardownCallable25from .typing import TemplateContextProcessorCallable26from .typing import URLDefaultCallable27from .typing import URLValuePreprocessorCallable2223if t.TYPE_CHECKING:24 from .wrappers import Response31 from .typing import ErrorHandlerCallable2526# a singleton sentinel value for parameter defaults27_sentinel = object()28
106 unmodified lines
135 #:136 #: This data structure is internal. It should not be modified137 #: directly and its format may change at any time.138 self.error_handler_spec: t.Dict[146 AppOrBlueprintKey,147 t.Dict[t.Optional[int], t.Dict[t.Type[Exception], "ErrorHandlerCallable"]],139 ft.AppOrBlueprintKey,140 t.Dict[t.Optional[int], t.Dict[t.Type[Exception], ft.ErrorHandlerCallable]],141 ] = defaultdict(lambda: defaultdict(dict))142143 #: A data structure of functions to call at the beginning of144 #: each request, in the format ``{scope: [functions]}``. The
5 unmodified lines
150 #:151 #: This data structure is internal. It should not be modified152 #: directly and its format may change at any time.153 self.before_request_funcs: t.Dict[161 AppOrBlueprintKey, t.List[BeforeRequestCallable]154 ft.AppOrBlueprintKey, t.List[ft.BeforeRequestCallable]155 ] = defaultdict(list)156157 #: A data structure of functions to call at the end of each158 #: request, in the format ``{scope: [functions]}``. The
5 unmodified lines
164 #:165 #: This data structure is internal. It should not be modified166 #: directly and its format may change at any time.167 self.after_request_funcs: t.Dict[175 AppOrBlueprintKey, t.List[AfterRequestCallable]168 ft.AppOrBlueprintKey, t.List[ft.AfterRequestCallable]169 ] = defaultdict(list)170171 #: A data structure of functions to call at the end of each172 #: request even if an exception is raised, in the format
6 unmodified lines
179 #:180 #: This data structure is internal. It should not be modified181 #: directly and its format may change at any time.182 self.teardown_request_funcs: t.Dict[190 AppOrBlueprintKey, t.List[TeardownCallable]183 ft.AppOrBlueprintKey, t.List[ft.TeardownCallable]184 ] = defaultdict(list)185186 #: A data structure of functions to call to pass extra context187 #: values when rendering templates, in the format
6 unmodified lines
194 #:195 #: This data structure is internal. It should not be modified196 #: directly and its format may change at any time.197 self.template_context_processors: t.Dict[205 AppOrBlueprintKey, t.List[TemplateContextProcessorCallable]198 ft.AppOrBlueprintKey, t.List[ft.TemplateContextProcessorCallable]199 ] = defaultdict(list, {None: [_default_template_ctx_processor]})200201 #: A data structure of functions to call to modify the keyword202 #: arguments passed to the view function, in the format
6 unmodified lines
209 #:210 #: This data structure is internal. It should not be modified211 #: directly and its format may change at any time.212 self.url_value_preprocessors: t.Dict[220 AppOrBlueprintKey,221 t.List[URLValuePreprocessorCallable],213 ft.AppOrBlueprintKey,214 t.List[ft.URLValuePreprocessorCallable],215 ] = defaultdict(list)216217 #: A data structure of functions to call to modify the keyword218 #: arguments when generating URLs, in the format
6 unmodified lines
225 #:226 #: This data structure is internal. It should not be modified227 #: directly and its format may change at any time.228 self.url_default_functions: t.Dict[236 AppOrBlueprintKey, t.List[URLDefaultCallable]229 ft.AppOrBlueprintKey, t.List[ft.URLDefaultCallable]230 ] = defaultdict(list)231232 def __repr__(self) -> str:233 return f"<{type(self).__name__} {self.name!r}>"
292 unmodified lines
526527 return decorator528529 @setupmethod537 def before_request(self, f: BeforeRequestCallable) -> BeforeRequestCallable:530 def before_request(self, f: ft.BeforeRequestCallable) -> ft.BeforeRequestCallable:531 """Register a function to run before each request.532533 For example, this can be used to open a database connection, or534 to load the logged in user from the session.
13 unmodified lines
548 self.before_request_funcs.setdefault(None, []).append(f)549 return f550551 @setupmethod559 def after_request(self, f: AfterRequestCallable) -> AfterRequestCallable:552 def after_request(self, f: ft.AfterRequestCallable) -> ft.AfterRequestCallable:553 """Register a function to run after each request to this object.554555 The function is called with the response object, and must return556 a response object. This allows the functions to modify or
7 unmodified lines
564 self.after_request_funcs.setdefault(None, []).append(f)565 return f566567 @setupmethod575 def teardown_request(self, f: TeardownCallable) -> TeardownCallable:568 def teardown_request(self, f: ft.TeardownCallable) -> ft.TeardownCallable:569 """Register a function to be run at the end of each request,570 regardless of whether there was an exception or not. These functions571 are executed when the request context is popped, even if not an572 actual request was performed.
31 unmodified lines
604 return f605606 @setupmethod607 def context_processor(615 self, f: TemplateContextProcessorCallable616 ) -> TemplateContextProcessorCallable:608 self, f: ft.TemplateContextProcessorCallable609 ) -> ft.TemplateContextProcessorCallable:610 """Registers a template context processor function."""611 self.template_context_processors[None].append(f)612 return f613614 @setupmethod615 def url_value_preprocessor(623 self, f: URLValuePreprocessorCallable624 ) -> URLValuePreprocessorCallable:616 self, f: ft.URLValuePreprocessorCallable617 ) -> ft.URLValuePreprocessorCallable:618 """Register a URL value preprocessor function for all view619 functions in the application. These functions will be called before the620 :meth:`before_request` functions.621
8 unmodified lines
630 self.url_value_preprocessors[None].append(f)631 return f632633 @setupmethod641 def url_defaults(self, f: URLDefaultCallable) -> URLDefaultCallable:634 def url_defaults(self, f: ft.URLDefaultCallable) -> ft.URLDefaultCallable:635 """Callback function for URL defaults for all view functions of the636 application. It's called with the endpoint and values and should637 update the values passed in place.638 """
2 unmodified lines
641642 @setupmethod643 def errorhandler(644 self, code_or_exception: t.Union[t.Type[Exception], int]652 ) -> t.Callable[["ErrorHandlerCallable"], "ErrorHandlerCallable"]:645 ) -> t.Callable[[ft.ErrorHandlerCallable], ft.ErrorHandlerCallable]:646 """Register a function to handle errors by code or exception class.647648 A decorator that is used to register a function given an649 error code. Example::
21 unmodified lines
671 :param code_or_exception: the code as integer for the handler, or672 an arbitrary exception673 """674682 def decorator(f: "ErrorHandlerCallable") -> "ErrorHandlerCallable":675 def decorator(f: ft.ErrorHandlerCallable) -> ft.ErrorHandlerCallable:676 self.register_error_handler(code_or_exception, f)677 return f678679 return decorator
1 unmodified line
681 @setupmethod682 def register_error_handler(683 self,684 code_or_exception: t.Union[t.Type[Exception], int],692 f: "ErrorHandlerCallable",685 f: ft.ErrorHandlerCallable,686 ) -> None:687 """Alternative error attach function to the :meth:`errorhandler`688 decorator that is more straightforward to use for non decorator689 usage.
173 unmodified lines
modified:src/flask/typing.py+7 added-2 removed
2 unmodified lines
34if t.TYPE_CHECKING:5 from _typeshed.wsgi import WSGIApplication # noqa: F4016 from werkzeug.datastructures import Headers # noqa: F4017 from werkzeug.wrappers.response import Response # noqa: F4017 from werkzeug.wrappers import Response # noqa: F40189# The possible types that are directly convertible or are a Response object.10ResponseValue = t.Union[11 "Response",
22 unmodified lines
34 t.Tuple[ResponseValue, StatusCode, HeadersValue],35 "WSGIApplication",36]3738# Allow any subclass of werkzeug.Response, such as the one from Flask,39# as a callback argument. Using werkzeug.Response directly makes a40# callback annotated with flask.Response fail type checking.41ResponseClass = t.TypeVar("ResponseClass", bound="Response")4243AppOrBlueprintKey = t.Optional[str] # The App key is None, whereas blueprints are named39AfterRequestCallable = t.Callable[["Response"], "Response"]44AfterRequestCallable = t.Callable[[ResponseClass], ResponseClass]45BeforeFirstRequestCallable = t.Callable[[], None]46BeforeRequestCallable = t.Callable[[], t.Optional[ResponseReturnValue]]47TeardownCallable = t.Callable[[t.Optional[BaseException]], None]48TemplateContextProcessorCallable = t.Callable[[], t.Dict[str, t.Any]]
12 unmodified lines
modified:src/flask/views.py+4 added-4 removed
1import typing as t23from . import typing as ft4from .globals import current_app5from .globals import request5from .typing import ResponseReturnValue678http_method_funcs = frozenset(9 ["get", "post", "head", "options", "delete", "put", "trace", "patch"]
48 unmodified lines
58 #:59 #: .. versionadded:: 0.860 decorators: t.List[t.Callable] = []6162 def dispatch_request(self) -> ResponseReturnValue:62 def dispatch_request(self) -> ft.ResponseReturnValue:63 """Subclasses have to override this method to implement the64 actual view function code. This method is called with all65 the arguments from the URL rule.66 """
11 unmodified lines
78 The arguments passed to :meth:`as_view` are forwarded to the79 constructor of the class.80 """8182 def view(*args: t.Any, **kwargs: t.Any) -> ResponseReturnValue:82 def view(*args: t.Any, **kwargs: t.Any) -> ft.ResponseReturnValue:83 self = view.view_class(*class_args, **class_kwargs) # type: ignore84 return current_app.ensure_sync(self.dispatch_request)(*args, **kwargs)8586 if cls.decorators:
58 unmodified lines
145146 app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))147 """148149 def dispatch_request(self, *args: t.Any, **kwargs: t.Any) -> ResponseReturnValue:149 def dispatch_request(self, *args: t.Any, **kwargs: t.Any) -> ft.ResponseReturnValue:150 meth = getattr(self, request.method.lower(), None)151152 # If the request method is HEAD and we don't have a handler for it153 # retry with GET.
5 unmodified lines
modified:CHANGES.rst+1 added
5 unmodified lines
6Unreleased78- Inline some optional imports that are only used for certain CLI9 commands. :pr:`4606`10- Relax type annotation for ``after_request`` functions. :issue:`4600`111213Version 2.1.214-------------
1280 unmodified lines