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
Provenance
- Commit
83e9680- Tree
42ae50c- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
a4f63e0- Parent 2
61f62e6
7 files changed+85 added−98 removed
modified:src/flask/app.py+26 added-30 removed
24 unmodified lines25 from werkzeug.wrappers import Response as BaseResponse26 27 from . import cli28 from . import json29+from . import typing as ft30 from .config import Config31 from .config import ConfigAttribute32 from .ctx import _AppCtxGlobals33 from .ctx import AppContext24 unmodified lines58 from .signals import request_started59 from .signals import request_tearing_down60 from .templating import DispatchingJinjaLoader61 from .templating import Environment61-from .typing import BeforeFirstRequestCallable62-from .typing import ResponseReturnValue63-from .typing import TeardownCallable64-from .typing import TemplateFilterCallable65-from .typing import TemplateGlobalCallable66-from .typing import TemplateTestCallable62 from .wrappers import Request63 from .wrappers import Response64 65 if t.TYPE_CHECKING:66 import typing_extensions as te67 from .blueprints import Blueprint68 from .testing import FlaskClient69 from .testing import FlaskCliRunner75- from .typing import ErrorHandlerCallable70 71 if sys.version_info >= (3, 8):72 iscoroutinefunction = inspect.iscoroutinefunction73 else:355 unmodified lines429 #: 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] = []434 435 #: 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] = []442 443 #: A list of shell context processor functions that should be run444 #: when a shell context is created.445 #:643 unmodified lines1089 1090 @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 lines1102 :param name: the optional name of the filter, otherwise the1103 function name will be used.1104 """1105 1112- def decorator(f: TemplateFilterCallable) -> TemplateFilterCallable:1106+ def decorator(f: ft.TemplateFilterCallable) -> ft.TemplateFilterCallable:1107 self.add_template_filter(f, name=name)1108 return f1109 1110 return decorator1111 1112 @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 lines1123 1124 @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 lines1143 :param name: the optional name of the test, otherwise the1144 function name will be used.1145 """1146 1153- def decorator(f: TemplateTestCallable) -> TemplateTestCallable:1147+ def decorator(f: ft.TemplateTestCallable) -> ft.TemplateTestCallable:1148 self.add_template_test(f, name=name)1149 return f1150 1151 return decorator1152 1153 @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 lines1166 1167 @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 lines1181 :param name: the optional name of the global function, otherwise the1182 function name will be used.1183 """1184 1191- def decorator(f: TemplateGlobalCallable) -> TemplateGlobalCallable:1185+ def decorator(f: ft.TemplateGlobalCallable) -> ft.TemplateGlobalCallable:1186 self.add_template_global(f, name=name)1187 return f1188 1189 return decorator1190 1191 @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 lines1203 self.jinja_env.globals[name or f.__name__] = f1204 1205 @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.1211 1212 The function will be called without any arguments and its return4 unmodified lines1217 self.before_first_request_funcs.append(f)1218 return f1219 1220 @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 lines1258 """1259 self.shell_context_processors.append(f)1260 return f1261 1268- 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 lines1283 return None1284 1285 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 lines1353 return False1354 1355 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 either61 unmodified lines1423 1424 raise e1425 1426 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)1430 1431 if handler is not None:45 unmodified lines1477 from .debughelpers import FormDataRoutingRedirect1478 1479 raise FormDataRoutingRedirect(request)1480 1487- 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 lines1520 return self.finalize_request(rv)1521 1522 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 the94 unmodified lines1623 ) from None1624 1625 return asgiref_async_to_sync(func)1626 1633- 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`.1630 1631 :param rv: the return value from the view function. The view function83 unmodified lines1715 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 lines1833 raise1834 1835 raise error1836 1841- 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 linesmodified:src/flask/blueprints.py+23 added-31 removed
1 unmodified line2 import typing as t3 from collections import defaultdict4 from functools import update_wrapper5 6+from . import typing as ft7 from .scaffold import _endpoint_from_view_func8 from .scaffold import _sentinel9 from .scaffold import Scaffold9-from .typing import AfterRequestCallable10-from .typing import BeforeFirstRequestCallable11-from .typing import BeforeRequestCallable12-from .typing import TeardownCallable13-from .typing import TemplateContextProcessorCallable14-from .typing import TemplateFilterCallable15-from .typing import TemplateGlobalCallable16-from .typing import TemplateTestCallable17-from .typing import URLDefaultCallable18-from .typing import URLValuePreprocessorCallable10 11 if t.TYPE_CHECKING:12 from .app import Flask22- from .typing import ErrorHandlerCallable13 14 DeferredSetupFunction = t.Callable[["BlueprintSetupState"], t.Callable]15 16 391 unmodified lines408 )409 410 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.415 416 :param name: the optional name of the filter, otherwise the417 function name will be used.418 """419 430- def decorator(f: TemplateFilterCallable) -> TemplateFilterCallable:420+ def decorator(f: ft.TemplateFilterCallable) -> ft.TemplateFilterCallable:421 self.add_app_template_filter(f, name=name)422 return f423 424 return decorator425 426 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 lines440 self.record_once(register_template)441 442 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.447 448 .. versionadded:: 0.101 unmodified line450 :param name: the optional name of the test, otherwise the451 function name will be used.452 """453 464- def decorator(f: TemplateTestCallable) -> TemplateTestCallable:454+ def decorator(f: ft.TemplateTestCallable) -> ft.TemplateTestCallable:455 self.add_app_template_test(f, name=name)456 return f457 458 return decorator459 460 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 lines476 self.record_once(register_template)477 478 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.483 484 .. versionadded:: 0.101 unmodified line486 :param name: the optional name of the global, otherwise the487 function name will be used.488 """489 500- def decorator(f: TemplateGlobalCallable) -> TemplateGlobalCallable:490+ def decorator(f: ft.TemplateGlobalCallable) -> ft.TemplateGlobalCallable:491 self.add_app_template_global(f, name=name)492 return f493 494 return decorator495 496 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 lines510 state.app.jinja_env.globals[name or f.__name__] = f511 512 self.record_once(register_template)513 524- 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 line522 )523 return f524 525 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 f533 542- 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 f542 551- 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 lines550 )551 return f552 553 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 lines565 """Like :meth:`Flask.errorhandler` but for a blueprint. This566 handler is used for all requests, even if outside of the blueprint.567 """568 577- 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 f572 573 return decorator574 575 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 f583 592- 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 linemodified:src/flask/ctx.py+3 added-3 removed
3 unmodified lines4 from types import TracebackType5 6 from werkzeug.exceptions import HTTPException7 8+from . import typing as ft9 from .globals import _app_ctx_stack10 from .globals import _request_ctx_stack11 from .signals import appcontext_popped12 from .signals import appcontext_pushed12-from .typing import AfterRequestCallable13 14 if t.TYPE_CHECKING:15 from .app import Flask16 from .sessions import SessionMixin91 unmodified lines108 return f"<flask.g of {top.app.name!r}>"109 return object.__repr__(self)110 111 112-def after_this_request(f: AfterRequestCallable) -> AfterRequestCallable:112+def 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 lines340 341 # 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] = []345 346 @property347 def g(self) -> _AppCtxGlobals:348 import warnings165 unmodified linesmodified:src/flask/scaffold.py+21 added-28 removed
10 unmodified lines11 from jinja2 import FileSystemLoader12 from werkzeug.exceptions import default_exceptions13 from werkzeug.exceptions import HTTPException14 15+from . import typing as ft16 from .cli import AppGroup17 from .globals import current_app18 from .helpers import get_root_path19 from .helpers import locked_cached_property20 from .helpers import send_from_directory21 from .templating import _default_template_ctx_processor21-from .typing import AfterRequestCallable22-from .typing import AppOrBlueprintKey23-from .typing import BeforeRequestCallable24-from .typing import TeardownCallable25-from .typing import TemplateContextProcessorCallable26-from .typing import URLDefaultCallable27-from .typing import URLValuePreprocessorCallable22 23 if t.TYPE_CHECKING:24 from .wrappers import Response31- from .typing import ErrorHandlerCallable25 26 # a singleton sentinel value for parameter defaults27 _sentinel = object()28 106 unmodified lines135 #: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))142 143 #: A data structure of functions to call at the beginning of144 #: each request, in the format ``{scope: [functions]}``. The5 unmodified lines150 #: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)156 157 #: A data structure of functions to call at the end of each158 #: request, in the format ``{scope: [functions]}``. The5 unmodified lines164 #: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)170 171 #: A data structure of functions to call at the end of each172 #: request even if an exception is raised, in the format6 unmodified lines179 #: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)185 186 #: A data structure of functions to call to pass extra context187 #: values when rendering templates, in the format6 unmodified lines194 #: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]})200 201 #: A data structure of functions to call to modify the keyword202 #: arguments passed to the view function, in the format6 unmodified lines209 #: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)216 217 #: A data structure of functions to call to modify the keyword218 #: arguments when generating URLs, in the format6 unmodified lines225 #: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)231 232 def __repr__(self) -> str:233 return f"<{type(self).__name__} {self.name!r}>"292 unmodified lines526 527 return decorator528 529 @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.532 533 For example, this can be used to open a database connection, or534 to load the logged in user from the session.13 unmodified lines548 self.before_request_funcs.setdefault(None, []).append(f)549 return f550 551 @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.554 555 The function is called with the response object, and must return556 a response object. This allows the functions to modify or7 unmodified lines564 self.after_request_funcs.setdefault(None, []).append(f)565 return f566 567 @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 lines604 return f605 606 @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 f613 614 @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 lines630 self.url_value_preprocessors[None].append(f)631 return f632 633 @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 lines641 642 @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.647 648 A decorator that is used to register a function given an649 error code. Example::21 unmodified lines671 :param code_or_exception: the code as integer for the handler, or672 an arbitrary exception673 """674 682- def decorator(f: "ErrorHandlerCallable") -> "ErrorHandlerCallable":675+ def decorator(f: ft.ErrorHandlerCallable) -> ft.ErrorHandlerCallable:676 self.register_error_handler(code_or_exception, f)677 return f678 679 return decorator1 unmodified line681 @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 linesmodified:src/flask/typing.py+7 added-2 removed
2 unmodified lines3 4 if 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: F4018 9 # The possible types that are directly convertible or are a Response object.10 ResponseValue = t.Union[11 "Response",22 unmodified lines34 t.Tuple[ResponseValue, StatusCode, HeadersValue],35 "WSGIApplication",36 ]37 38+# 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.41+ResponseClass = t.TypeVar("ResponseClass", bound="Response")42+43 AppOrBlueprintKey = t.Optional[str] # The App key is None, whereas blueprints are named39-AfterRequestCallable = t.Callable[["Response"], "Response"]44+AfterRequestCallable = t.Callable[[ResponseClass], ResponseClass]45 BeforeFirstRequestCallable = t.Callable[[], None]46 BeforeRequestCallable = t.Callable[[], t.Optional[ResponseReturnValue]]47 TeardownCallable = t.Callable[[t.Optional[BaseException]], None]48 TemplateContextProcessorCallable = t.Callable[[], t.Dict[str, t.Any]]12 unmodified linesmodified:src/flask/views.py+4 added-4 removed
1 import typing as t2 3+from . import typing as ft4 from .globals import current_app5 from .globals import request5-from .typing import ResponseReturnValue6 7 8 http_method_funcs = frozenset(9 ["get", "post", "head", "options", "delete", "put", "trace", "patch"]48 unmodified lines58 #:59 #: .. versionadded:: 0.860 decorators: t.List[t.Callable] = []61 62- 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 lines78 The arguments passed to :meth:`as_view` are forwarded to the79 constructor of the class.80 """81 82- 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)85 86 if cls.decorators:58 unmodified lines145 146 app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))147 """148 149- 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)151 152 # If the request method is HEAD and we don't have a handler for it153 # retry with GET.5 unmodified linesmodified:CHANGES.rst+1 added
5 unmodified lines6 Unreleased7 8 - Inline some optional imports that are only used for certain CLI9 commands. :pr:`4606`10+- Relax type annotation for ``after_request`` functions. :issue:`4600`11 12 13 Version 2.1.214 -------------1280 unmodified lines