Merge pull request #5071 from pallets/future-annotations
Before adoption: this commit came in with the history the project adopted, so no landing records it.
use postponed evaluation of annotations
authored by David Lord · committed by GitHub · parents cfa863c, 44ffe6c · Browse files · 19 files·+277 added−262 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
19 files+277 added−262 removed
- other:+277 added−262 removed
Provenance
- Commit
a4ea5df- Tree
e48bb40- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
cfa863c- Parent 2
44ffe6c
19 files changed+277 added−262 removed
modified:src/flask/json/provider.py+2 added-2 removed
70 unmodified lines71 """72 return self.loads(fp.read(), **kwargs)73 74 def _prepare_response_obj(75- self, args: t.Tuple[t.Any, ...], kwargs: t.Dict[str, t.Any]75+ self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]76 ) -> t.Any:77 if args and kwargs:78 raise TypeError("app.json.response() takes either args or kwargs, not both")79 123 unmodified lines203 treat as a list to serialize.204 :param kwargs: Treat as a dict to serialize.205 """206 obj = self._prepare_response_obj(args, kwargs)207- dump_args: t.Dict[str, t.Any] = {}207+ dump_args: dict[str, t.Any] = {}208 209 if (self.compact is None and self._app.debug) or self.compact is False:210 dump_args.setdefault("indent", 2)211 else:5 unmodified linesmodified:src/flask/json/tag.py+10 added-8 removed
38 unmodified lines39 return OrderedDict(value)40 41 app.session_interface.serializer.register(TagOrderedDict, index=0)42 """43+from __future__ import annotations44+45 import typing as t46 from base64 import b64decode47 from base64 import b64encode48 from datetime import datetime13 unmodified lines62 __slots__ = ("serializer",)63 64 #: The tag to mark the serialized object with. If ``None``, this tag is65 #: only used as an intermediate step during tagging.64- key: t.Optional[str] = None66+ key: str | None = None67 66- def __init__(self, serializer: "TaggedJSONSerializer") -> None:68+ def __init__(self, serializer: TaggedJSONSerializer) -> None:69 """Create a tagger for the given serializer."""70 self.serializer = serializer71 72 def check(self, value: t.Any) -> bool:172 unmodified lines245 TagDateTime,246 ]247 248 def __init__(self) -> None:247- self.tags: t.Dict[str, JSONTag] = {}248- self.order: t.List[JSONTag] = []249+ self.tags: dict[str, JSONTag] = {}250+ self.order: list[JSONTag] = []251 252 for cls in self.default_tags:253 self.register(cls)254 255 def register(256 self,255- tag_class: t.Type[JSONTag],257+ tag_class: type[JSONTag],258 force: bool = False,257- index: t.Optional[int] = None,259+ index: int | None = None,260 ) -> None:261 """Register a new tag with this serializer.262 263 :param tag_class: tag class to register. Will be instantiated with this20 unmodified lines284 self.order.append(tag)285 else:286 self.order.insert(index, tag)287 286- def tag(self, value: t.Any) -> t.Dict[str, t.Any]:288+ def tag(self, value: t.Any) -> dict[str, t.Any]:289 """Convert a value to a tagged representation if necessary."""290 for tag in self.order:291 if tag.check(value):292 return tag.tag(value)293 294 return value295 294- def untag(self, value: t.Dict[str, t.Any]) -> t.Any:296+ def untag(self, value: dict[str, t.Any]) -> t.Any:297 """Convert a tagged representation back to the original type."""298 if len(value) != 1:299 return value300 14 unmodified linesmodified:src/flask/app.py+54 added-56 removed
1+from __future__ import annotations2+3 import functools4 import inspect5 import logging6 import os89 unmodified lines96 97 return inspect.iscoroutinefunction(func)98 99 98-def _make_timedelta(value: t.Union[timedelta, int, None]) -> t.Optional[timedelta]:100+def _make_timedelta(value: timedelta | int | None) -> timedelta | None:101 if value is None or isinstance(value, timedelta):102 return value103 104 return timedelta(seconds=value)176 unmodified lines281 permanent_session_lifetime = ConfigAttribute(282 "PERMANENT_SESSION_LIFETIME", get_converter=_make_timedelta283 )284 283- json_provider_class: t.Type[JSONProvider] = DefaultJSONProvider285+ json_provider_class: type[JSONProvider] = DefaultJSONProvider286 """A subclass of :class:`~flask.json.provider.JSONProvider`. An287 instance is created and assigned to :attr:`app.json` when creating288 the app.289 59 unmodified lines349 #: The :meth:`test_client` method creates an instance of this test350 #: client class. Defaults to :class:`~flask.testing.FlaskClient`.351 #:352 #: .. versionadded:: 0.7351- test_client_class: t.Optional[t.Type["FlaskClient"]] = None353+ test_client_class: type[FlaskClient] | None = None354 355 #: The :class:`~click.testing.CliRunner` subclass, by default356 #: :class:`~flask.testing.FlaskCliRunner` that is used by357 #: :meth:`test_cli_runner`. Its ``__init__`` method should take a358 #: Flask app object as the first argument.359 #:360 #: .. versionadded:: 1.0359- test_cli_runner_class: t.Optional[t.Type["FlaskCliRunner"]] = None361+ test_cli_runner_class: type[FlaskCliRunner] | None = None362 363 #: the session interface to use. By default an instance of364 #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.365 #:2 unmodified lines368 369 def __init__(370 self,371 import_name: str,370- static_url_path: t.Optional[str] = None,371- static_folder: t.Optional[t.Union[str, os.PathLike]] = "static",372- static_host: t.Optional[str] = None,372+ static_url_path: str | None = None,373+ static_folder: str | os.PathLike | None = "static",374+ static_host: str | None = None,375 host_matching: bool = False,376 subdomain_matching: bool = False,375- template_folder: t.Optional[t.Union[str, os.PathLike]] = "templates",376- instance_path: t.Optional[str] = None,377+ template_folder: str | os.PathLike | None = "templates",378+ instance_path: str | None = None,379 instance_relative_config: bool = False,378- root_path: t.Optional[str] = None,380+ root_path: str | None = None,381 ):382 super().__init__(383 import_name=import_name,384 static_folder=static_folder,51 unmodified lines436 #: returns ``None`` or raises a ``BuildError``, it is skipped.437 #: Otherwise, its return value is returned by ``url_for``.438 #:439 #: .. versionadded:: 0.9438- self.url_build_error_handlers: t.List[439- t.Callable[[Exception, str, t.Dict[str, t.Any]], str]440+ self.url_build_error_handlers: list[441+ t.Callable[[Exception, str, dict[str, t.Any]], str]442 ] = []443 444 #: A list of functions that are called when the application context445 #: is destroyed. Since the application context is also torn down446 #: if the request ends this is the place to store code that disconnects447 #: from databases.448 #:449 #: .. versionadded:: 0.9448- self.teardown_appcontext_funcs: t.List[ft.TeardownCallable] = []450+ self.teardown_appcontext_funcs: list[ft.TeardownCallable] = []451 452 #: A list of shell context processor functions that should be run453 #: when a shell context is created.454 #:455 #: .. versionadded:: 0.11454- self.shell_context_processors: t.List[ft.ShellContextProcessorCallable] = []456+ self.shell_context_processors: list[ft.ShellContextProcessorCallable] = []457 458 #: Maps registered blueprint names to blueprint objects. The459 #: dict retains the order the blueprints were registered in.460 #: Blueprints can be registered multiple times, this dict does461 #: not track how often they were attached.462 #:463 #: .. versionadded:: 0.7462- self.blueprints: t.Dict[str, "Blueprint"] = {}464+ self.blueprints: dict[str, Blueprint] = {}465 466 #: a place where extensions can store application specific state. For467 #: example this is where an extension could store database engines and468 #: similar things.266 unmodified lines735 736 :param context: the context as a dictionary that is updated in place737 to add extra variables.738 """737- names: t.Iterable[t.Optional[str]] = (None,)739+ names: t.Iterable[str | None] = (None,)740 741 # A template may be rendered outside a request context.742 if request:743 names = chain(names, reversed(request.blueprints))42 unmodified lines786 self.jinja_env.auto_reload = value787 788 def run(789 self,788- host: t.Optional[str] = None,789- port: t.Optional[int] = None,790- debug: t.Optional[bool] = None,790+ host: str | None = None,791+ port: int | None = None,792+ debug: bool | None = None,793 load_dotenv: bool = True,794 **options: t.Any,795 ) -> None:796 """Runs the application on a local development server.110 unmodified lines907 # reset normally. This makes it possible to restart the server908 # without reloader and that stuff from an interactive shell.909 self._got_first_request = False910 909- def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> "FlaskClient":911+ def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> FlaskClient:912 """Creates a test client for this application. For information913 about unit testing head over to :doc:`/testing`.914 915 Note that if you are testing for assertions or exceptions in your49 unmodified lines965 return cls( # type: ignore966 self, self.response_class, use_cookies=use_cookies, **kwargs967 )968 967- def test_cli_runner(self, **kwargs: t.Any) -> "FlaskCliRunner":969+ def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner:970 """Create a CLI runner for testing CLI commands.971 See :ref:`testing-cli`.972 973 Returns an instance of :attr:`test_cli_runner_class`, by default9 unmodified lines983 984 return cls(self, **kwargs) # type: ignore985 986 @setupmethod985- def register_blueprint(self, blueprint: "Blueprint", **options: t.Any) -> None:987+ def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:988 """Register a :class:`~flask.Blueprint` on the application. Keyword989 arguments passed to this method will override the defaults set on the990 blueprint.991 18 unmodified lines1010 .. versionadded:: 0.71011 """1012 blueprint.register(self, options)1013 1012- def iter_blueprints(self) -> t.ValuesView["Blueprint"]:1014+ def iter_blueprints(self) -> t.ValuesView[Blueprint]:1015 """Iterates over all blueprints by the order they were registered.1016 1017 .. versionadded:: 0.111018 """2 unmodified lines1021 @setupmethod1022 def add_url_rule(1023 self,1024 rule: str,1023- endpoint: t.Optional[str] = None,1024- view_func: t.Optional[ft.RouteCallable] = None,1025- provide_automatic_options: t.Optional[bool] = None,1025+ endpoint: str | None = None,1026+ view_func: ft.RouteCallable | None = None,1027+ provide_automatic_options: bool | None = None,1028 **options: t.Any,1029 ) -> None:1030 if endpoint is None:1031 endpoint = _endpoint_from_view_func(view_func) # type: ignore46 unmodified lines1078 self.view_functions[endpoint] = view_func1079 1080 @setupmethod1081 def template_filter(1080- self, name: t.Optional[str] = None1082+ self, name: str | None = None1083 ) -> t.Callable[[T_template_filter], T_template_filter]:1084 """A decorator that is used to register custom template filter.1085 You can specify a name for the filter, otherwise the function1086 name will be used. Example::13 unmodified lines1100 return decorator1101 1102 @setupmethod1103 def add_template_filter(1102- self, f: ft.TemplateFilterCallable, name: t.Optional[str] = None1104+ self, f: ft.TemplateFilterCallable, name: str | None = None1105 ) -> None:1106 """Register a custom template filter. Works exactly like the1107 :meth:`template_filter` decorator.1108 3 unmodified lines1112 self.jinja_env.filters[name or f.__name__] = f1113 1114 @setupmethod1115 def template_test(1114- self, name: t.Optional[str] = None1116+ self, name: str | None = None1117 ) -> t.Callable[[T_template_test], T_template_test]:1118 """A decorator that is used to register custom template test.1119 You can specify a name for the test, otherwise the function1120 name will be used. Example::20 unmodified lines1141 return decorator1142 1143 @setupmethod1144 def add_template_test(1143- self, f: ft.TemplateTestCallable, name: t.Optional[str] = None1145+ self, f: ft.TemplateTestCallable, name: str | None = None1146 ) -> None:1147 """Register a custom template test. Works exactly like the1148 :meth:`template_test` decorator.1149 5 unmodified lines1155 self.jinja_env.tests[name or f.__name__] = f1156 1157 @setupmethod1158 def template_global(1157- self, name: t.Optional[str] = None1159+ self, name: str | None = None1160 ) -> t.Callable[[T_template_global], T_template_global]:1161 """A decorator that is used to register a custom template global function.1162 You can specify a name for the global function, otherwise the function1163 name will be used. Example::15 unmodified lines1179 return decorator1180 1181 @setupmethod1182 def add_template_global(1181- self, f: ft.TemplateGlobalCallable, name: t.Optional[str] = None1183+ self, f: ft.TemplateGlobalCallable, name: str | None = None1184 ) -> None:1185 """Register a custom template global function. Works exactly like the1186 :meth:`template_global` decorator.1187 48 unmodified lines1236 """1237 self.shell_context_processors.append(f)1238 return f1239 1238- def _find_error_handler(self, e: Exception) -> t.Optional[ft.ErrorHandlerCallable]:1240+ def _find_error_handler(self, e: Exception) -> ft.ErrorHandlerCallable | None:1241 """Return a registered error handler for an exception in this order:1242 blueprint handler for a specific code, app handler for a specific code,1243 blueprint handler for an exception class, app handler for an exception1244 class, or ``None`` if a suitable handler is not found.16 unmodified lines1261 return None1262 1263 def handle_http_exception(1264 self, e: HTTPException1263- ) -> t.Union[HTTPException, ft.ResponseReturnValue]:1265+ ) -> HTTPException | ft.ResponseReturnValue:1266 """Handles an HTTP exception. By default this will invoke the1267 registered error handlers and fall back to returning the1268 exception as response.1269 61 unmodified lines1331 return False1332 1333 def handle_user_exception(1334 self, e: Exception1333- ) -> t.Union[HTTPException, ft.ResponseReturnValue]:1335+ ) -> HTTPException | ft.ResponseReturnValue:1336 """This method is called whenever an exception occurs that1337 should be handled. A special case is :class:`~werkzeug1338 .exceptions.HTTPException` which is forwarded to the1339 :meth:`handle_http_exception` method. This function will either65 unmodified lines1405 1406 raise e1407 1408 self.log_exception(exc_info)1407- server_error: t.Union[InternalServerError, ft.ResponseReturnValue]1409+ server_error: InternalServerError | ft.ResponseReturnValue1410 server_error = InternalServerError(original_exception=e)1411 handler = self._find_error_handler(server_error)1412 1413 if handler is not None:2 unmodified lines1416 return self.finalize_request(server_error, from_error_handler=True)1417 1418 def log_exception(1419 self,1418- exc_info: t.Union[1419- t.Tuple[type, BaseException, TracebackType], t.Tuple[None, None, None]1420- ],1420+ exc_info: (tuple[type, BaseException, TracebackType] | tuple[None, None, None]),1421 ) -> None:1422 """Logs an exception. This is called by :meth:`handle_exception`1423 if debugging is disabled and right before the handler is called.1424 The default implementation logs the exception as error on the4 unmodified lines1429 self.logger.error(1430 f"Exception on {request.path} [{request.method}]", exc_info=exc_info1431 )1432 1433- def raise_routing_exception(self, request: Request) -> "te.NoReturn":1433+ def raise_routing_exception(self, request: Request) -> te.NoReturn:1434 """Intercept routing exceptions and possibly do something else.1435 1436 In debug mode, intercept a routing redirect and replace it with1437 an error if the body will be discarded.41 unmodified lines1479 and req.method == "OPTIONS"1480 ):1481 return self.make_default_options_response()1482 # otherwise dispatch to the handler for that endpoint1483- view_args: t.Dict[str, t.Any] = req.view_args # type: ignore[assignment]1483+ view_args: dict[str, t.Any] = req.view_args # type: ignore[assignment]1484 return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)1485 1486 def full_dispatch_request(self) -> Response:1487 """Dispatches the request and on top of that performs request14 unmodified lines1502 return self.finalize_request(rv)1503 1504 def finalize_request(1505 self,1506- rv: t.Union[ft.ResponseReturnValue, HTTPException],1506+ rv: ft.ResponseReturnValue | HTTPException,1507 from_error_handler: bool = False,1508 ) -> Response:1509 """Given the return value from a view function this finalizes1510 the request by converting it into a response and invoking the33 unmodified lines1544 rv = self.response_class()1545 rv.allow.update(methods)1546 return rv1547 1548- def should_ignore_error(self, error: t.Optional[BaseException]) -> bool:1548+ def should_ignore_error(self, error: BaseException | None) -> bool:1549 """This is called to figure out if an error should be ignored1550 or not as far as the teardown system is concerned. If this1551 function returns ``True`` then the teardown handlers will not be1552 passed the error.42 unmodified lines1595 def url_for(1596 self,1597 endpoint: str,1598 *,1599- _anchor: t.Optional[str] = None,1600- _method: t.Optional[str] = None,1601- _scheme: t.Optional[str] = None,1602- _external: t.Optional[bool] = None,1599+ _anchor: str | None = None,1600+ _method: str | None = None,1601+ _scheme: str | None = None,1602+ _external: bool | None = None,1603 **values: t.Any,1604 ) -> str:1605 """Generate a URL to the given endpoint with the given values.1606 263 unmodified lines1870 rv.headers.update(headers) # type: ignore[arg-type]1871 1872 return rv1873 1874- def create_url_adapter(1875- self, request: t.Optional[Request]1876- ) -> t.Optional[MapAdapter]:1874+ def create_url_adapter(self, request: Request | None) -> MapAdapter | None:1875 """Creates a URL adapter for the given request. The URL adapter1876 is created at a point where the request context is not yet set1877 up so the request is passed explicitly.1878 38 unmodified lines1917 automatically called on URL building.1918 1919 .. versionadded:: 0.71920 """1923- names: t.Iterable[t.Optional[str]] = (None,)1921+ names: t.Iterable[str | None] = (None,)1922 1923 # url_for may be called outside a request context, parse the1924 # passed endpoint instead of using request.blueprints.1925 if "." in endpoint:6 unmodified lines1932 for func in self.url_default_functions[name]:1933 func(endpoint, values)1934 1935 def handle_url_build_error(1938- self, error: BuildError, endpoint: str, values: t.Dict[str, t.Any]1936+ self, error: BuildError, endpoint: str, values: dict[str, t.Any]1937 ) -> str:1938 """Called by :meth:`.url_for` if a1939 :exc:`~werkzeug.routing.BuildError` was raised. If this returns1940 a value, it will be returned by ``url_for``, otherwise the error24 unmodified lines1965 raise1966 1967 raise error1968 1971- def preprocess_request(self) -> t.Optional[ft.ResponseReturnValue]:1969+ def preprocess_request(self) -> ft.ResponseReturnValue | None:1970 """Called before the request is dispatched. Calls1971 :attr:`url_value_preprocessors` registered with the app and the1972 current blueprint (if any). Then calls :attr:`before_request_funcs`1973 registered with the app and the blueprint.47 unmodified lines2021 2022 return response2023 2024 def do_teardown_request(2027- self, exc: t.Optional[BaseException] = _sentinel # type: ignore2025+ self, exc: BaseException | None = _sentinel # type: ignore2026 ) -> None:2027 """Called after the request is dispatched and the response is2028 returned, right before the request context is popped.2029 24 unmodified lines2054 2055 request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)2056 2057 def do_teardown_appcontext(2060- self, exc: t.Optional[BaseException] = _sentinel # type: ignore2058+ self, exc: BaseException | None = _sentinel # type: ignore2059 ) -> None:2060 """Called right before the application context is popped.2061 2062 When handling a request, the application context is popped134 unmodified lines2197 a list of headers, and an optional exception context to2198 start the response.2199 """2200 ctx = self.request_context(environ)2203- error: t.Optional[BaseException] = None2201+ error: BaseException | None = None2202 try:2203 try:2204 ctx.push()2205 response = self.full_dispatch_request()23 unmodified linesmodified:src/flask/blueprints.py+29 added-27 removed
1+from __future__ import annotations2+3 import os4 import typing as t5 from collections import defaultdict6 from functools import update_wrapper32 unmodified lines39 """40 41 def __init__(42 self,41- blueprint: "Blueprint",42- app: "Flask",43+ blueprint: Blueprint,44+ app: Flask,45 options: t.Any,46 first_registration: bool,47 ) -> None:48 #: a reference to the current application37 unmodified lines86 87 def add_url_rule(88 self,89 rule: str,88- endpoint: t.Optional[str] = None,89- view_func: t.Optional[t.Callable] = None,90+ endpoint: str | None = None,91+ view_func: t.Callable | None = None,92 **options: t.Any,93 ) -> None:94 """A helper method to register a rule (and optionally a view function)95 to the application. The endpoint is automatically prefixed with the78 unmodified lines174 def __init__(175 self,176 name: str,177 import_name: str,176- static_folder: t.Optional[t.Union[str, os.PathLike]] = None,177- static_url_path: t.Optional[str] = None,178- template_folder: t.Optional[t.Union[str, os.PathLike]] = None,179- url_prefix: t.Optional[str] = None,180- subdomain: t.Optional[str] = None,181- url_defaults: t.Optional[dict] = None,182- root_path: t.Optional[str] = None,183- cli_group: t.Optional[str] = _sentinel, # type: ignore178+ static_folder: str | os.PathLike | None = None,179+ static_url_path: str | None = None,180+ template_folder: str | os.PathLike | None = None,181+ url_prefix: str | None = None,182+ subdomain: str | None = None,183+ url_defaults: dict | None = None,184+ root_path: str | None = None,185+ cli_group: str | None = _sentinel, # type: ignore186 ):187 super().__init__(188 import_name=import_name,189 static_folder=static_folder,10 unmodified lines200 201 self.name = name202 self.url_prefix = url_prefix203 self.subdomain = subdomain202- self.deferred_functions: t.List[DeferredSetupFunction] = []204+ self.deferred_functions: list[DeferredSetupFunction] = []205 206 if url_defaults is None:207 url_defaults = {}208 209 self.url_values_defaults = url_defaults210 self.cli_group = cli_group209- self._blueprints: t.List[t.Tuple["Blueprint", dict]] = []211+ self._blueprints: list[tuple[Blueprint, dict]] = []212 213 def _check_setup_finished(self, f_name: str) -> None:214 if self._got_registered_once:215 raise AssertionError(27 unmodified lines243 244 self.record(update_wrapper(wrapper, func))245 246 def make_setup_state(245- self, app: "Flask", options: dict, first_registration: bool = False247+ self, app: Flask, options: dict, first_registration: bool = False248 ) -> BlueprintSetupState:249 """Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`250 object that is later passed to the register callback functions.251 Subclasses can override this to return a subclass of the setup state.252 """253 return BlueprintSetupState(self, app, options, first_registration)254 255 @setupmethod254- def register_blueprint(self, blueprint: "Blueprint", **options: t.Any) -> None:256+ def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:257 """Register a :class:`~flask.Blueprint` on this blueprint. Keyword258 arguments passed to this method will override the defaults set259 on the blueprint.260 8 unmodified lines269 if blueprint is self:270 raise ValueError("Cannot register a blueprint on itself")271 self._blueprints.append((blueprint, options))272 271- def register(self, app: "Flask", options: dict) -> None:273+ def register(self, app: Flask, options: dict) -> None:274 """Called by :meth:`Flask.register_blueprint` to register all275 views and callbacks registered on the blueprint with the276 application. Creates a :class:`.BlueprintSetupState` and calls277 each :meth:`record` callback with it.131 unmodified lines409 @setupmethod410 def add_url_rule(411 self,412 rule: str,411- endpoint: t.Optional[str] = None,412- view_func: t.Optional[ft.RouteCallable] = None,413- provide_automatic_options: t.Optional[bool] = None,413+ endpoint: str | None = None,414+ view_func: ft.RouteCallable | None = None,415+ provide_automatic_options: bool | None = None,416 **options: t.Any,417 ) -> None:418 """Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for419 full documentation.18 unmodified lines438 )439 440 @setupmethod441 def app_template_filter(440- self, name: t.Optional[str] = None442+ self, name: str | None = None443 ) -> t.Callable[[T_template_filter], T_template_filter]:444 """Register a template filter, available in any template rendered by the445 application. Equivalent to :meth:`.Flask.template_filter`.446 8 unmodified lines455 return decorator456 457 @setupmethod458 def add_app_template_filter(457- self, f: ft.TemplateFilterCallable, name: t.Optional[str] = None459+ self, f: ft.TemplateFilterCallable, name: str | None = None460 ) -> None:461 """Register a template filter, available in any template rendered by the462 application. Works like the :meth:`app_template_filter` decorator. Equivalent to463 :meth:`.Flask.add_template_filter`.8 unmodified lines472 self.record_once(register_template)473 474 @setupmethod475 def app_template_test(474- self, name: t.Optional[str] = None476+ self, name: str | None = None477 ) -> t.Callable[[T_template_test], T_template_test]:478 """Register a template test, available in any template rendered by the479 application. Equivalent to :meth:`.Flask.template_test`.480 10 unmodified lines491 return decorator492 493 @setupmethod494 def add_app_template_test(493- self, f: ft.TemplateTestCallable, name: t.Optional[str] = None495+ self, f: ft.TemplateTestCallable, name: str | None = None496 ) -> None:497 """Register a template test, available in any template rendered by the498 application. Works like the :meth:`app_template_test` decorator. Equivalent to499 :meth:`.Flask.add_template_test`.10 unmodified lines510 self.record_once(register_template)511 512 @setupmethod513 def app_template_global(512- self, name: t.Optional[str] = None514+ self, name: str | None = None515 ) -> t.Callable[[T_template_global], T_template_global]:516 """Register a template global, available in any template rendered by the517 application. Equivalent to :meth:`.Flask.template_global`.518 10 unmodified lines529 return decorator530 531 @setupmethod532 def add_app_template_global(531- self, f: ft.TemplateGlobalCallable, name: t.Optional[str] = None533+ self, f: ft.TemplateGlobalCallable, name: str | None = None534 ) -> None:535 """Register a template global, available in any template rendered by the536 application. Works like the :meth:`app_template_global` decorator. Equivalent to537 :meth:`.Flask.add_template_global`.52 unmodified lines590 return f591 592 @setupmethod593 def app_errorhandler(592- self, code: t.Union[t.Type[Exception], int]594+ self, code: type[Exception] | int595 ) -> t.Callable[[T_error_handler], T_error_handler]:596 """Like :meth:`errorhandler`, but for every request, not only those handled by597 the blueprint. Equivalent to :meth:`.Flask.errorhandler`.598 """28 unmodified linesmodified:src/flask/cli.py+1 added-1 removed
283 unmodified lines284 #: the instance of the application.285 self.create_app = create_app286 #: A dictionary with arbitrary data that can be associated with287 #: this script info.288- self.data: t.Dict[t.Any, t.Any] = {}288+ self.data: dict[t.Any, t.Any] = {}289 self.set_debug_flag = set_debug_flag290 self._loaded_app: Flask | None = None291 292 def load_app(self) -> Flask:775 unmodified linesmodified:src/flask/config.py+8 added-6 removed
1+from __future__ import annotations2+3 import errno4 import json5 import os6 import types4 unmodified lines11 12 class ConfigAttribute:13 """Makes an attribute forward to the config"""14 13- def __init__(self, name: str, get_converter: t.Optional[t.Callable] = None) -> None:15+ def __init__(self, name: str, get_converter: t.Callable | None = None) -> None:16 self.__name__ = name17 self.get_converter = get_converter18 19 def __get__(self, obj: t.Any, owner: t.Any = None) -> t.Any:51 unmodified lines71 the application's :attr:`~flask.Flask.root_path`.72 :param defaults: an optional dictionary of default values73 """74 73- def __init__(self, root_path: str, defaults: t.Optional[dict] = None) -> None:75+ def __init__(self, root_path: str, defaults: dict | None = None) -> None:76 super().__init__(defaults or {})77 self.root_path = root_path78 79 def from_envvar(self, variable_name: str, silent: bool = False) -> bool:112 unmodified lines192 raise193 self.from_object(d)194 return True195 194- def from_object(self, obj: t.Union[object, str]) -> None:196+ def from_object(self, obj: object | str) -> None:197 """Updates the values from the given object. An object can be of one198 of the following two types:199 200 - a string: in this case the object with that name will be imported78 unmodified lines279 280 return self.from_mapping(obj)281 282 def from_mapping(281- self, mapping: t.Optional[t.Mapping[str, t.Any]] = None, **kwargs: t.Any283+ self, mapping: t.Mapping[str, t.Any] | None = None, **kwargs: t.Any284 ) -> bool:285 """Updates the config like :meth:`update` ignoring items with286 non-upper keys.287 288 :return: Always returns ``True``.289 290 .. versionadded:: 0.11291 """290- mappings: t.Dict[str, t.Any] = {}292+ mappings: dict[str, t.Any] = {}293 if mapping is not None:294 mappings.update(mapping)295 mappings.update(kwargs)296 for key, value in mappings.items():2 unmodified lines299 return True300 301 def get_namespace(302 self, namespace: str, lowercase: bool = True, trim_namespace: bool = True301- ) -> t.Dict[str, t.Any]:303+ ) -> dict[str, t.Any]:304 """Returns a dictionary containing a subset of configuration options305 that match the specified namespace/prefix. Example usage::306 307 app.config['IMAGE_STORE_TYPE'] = 'fs'38 unmodified linesmodified:src/flask/ctx.py+23 added-21 removed
1+from __future__ import annotations2+3 import contextvars4 import sys5 import typing as t6 from functools import update_wrapper54 unmodified lines61 del self.__dict__[name]62 except KeyError:63 raise AttributeError(name) from None64 63- def get(self, name: str, default: t.Optional[t.Any] = None) -> t.Any:65+ def get(self, name: str, default: t.Any | None = None) -> t.Any:66 """Get an attribute by name, or a default value. Like67 :meth:`dict.get`.68 69 :param name: Name of attribute to get.164 unmodified lines234 one is not already active. An app context is also pushed when235 running CLI commands.236 """237 236- def __init__(self, app: "Flask") -> None:238+ def __init__(self, app: Flask) -> None:239 self.app = app240 self.url_adapter = app.create_url_adapter(None)241 self.g: _AppCtxGlobals = app.app_ctx_globals_class()240- self._cv_tokens: t.List[contextvars.Token] = []242+ self._cv_tokens: list[contextvars.Token] = []243 244 def push(self) -> None:245 """Binds the app context to the current context."""246 self._cv_tokens.append(_cv_app.set(self))247 appcontext_pushed.send(self.app, _async_wrapper=self.app.ensure_sync)248 247- def pop(self, exc: t.Optional[BaseException] = _sentinel) -> None: # type: ignore249+ def pop(self, exc: BaseException | None = _sentinel) -> None: # type: ignore250 """Pops the app context."""251 try:252 if len(self._cv_tokens) == 1:253 if exc is _sentinel:9 unmodified lines263 )264 265 appcontext_popped.send(self.app, _async_wrapper=self.app.ensure_sync)266 265- def __enter__(self) -> "AppContext":267+ def __enter__(self) -> AppContext:268 self.push()269 return self270 271 def __exit__(272 self,271- exc_type: t.Optional[type],272- exc_value: t.Optional[BaseException],273- tb: t.Optional[TracebackType],273+ exc_type: type | None,274+ exc_value: BaseException | None,275+ tb: TracebackType | None,276 ) -> None:277 self.pop(exc_value)278 279 20 unmodified lines300 """301 302 def __init__(303 self,302- app: "Flask",304+ app: Flask,305 environ: dict,304- request: t.Optional["Request"] = None,305- session: t.Optional["SessionMixin"] = None,306+ request: Request | None = None,307+ session: SessionMixin | None = None,308 ) -> None:309 self.app = app310 if request is None:311 request = app.request_class(environ)3 unmodified lines315 try:316 self.url_adapter = app.create_url_adapter(self.request)317 except HTTPException as e:318 self.request.routing_exception = e317- self.flashes: t.Optional[t.List[t.Tuple[str, str]]] = None318- self.session: t.Optional["SessionMixin"] = session319+ self.flashes: list[tuple[str, str]] | None = None320+ self.session: SessionMixin | None = session321 # Functions that should be executed after the request on the response322 # object. These will be called before the regular "after_request"323 # functions.322- self._after_request_functions: t.List[ft.AfterRequestCallable] = []324+ self._after_request_functions: list[ft.AfterRequestCallable] = []325 324- self._cv_tokens: t.List[t.Tuple[contextvars.Token, t.Optional[AppContext]]] = []326+ self._cv_tokens: list[tuple[contextvars.Token, AppContext | None]] = []327 326- def copy(self) -> "RequestContext":328+ def copy(self) -> RequestContext:329 """Creates a copy of this request context with the same request object.330 This can be used to move a request context to a different greenlet.331 Because the actual request object is the same this cannot be used to332 move a request context to a different thread unless access to the50 unmodified lines383 # session is available in custom URL converters.384 if self.url_adapter is not None:385 self.match_request()386 385- def pop(self, exc: t.Optional[BaseException] = _sentinel) -> None: # type: ignore387+ def pop(self, exc: BaseException | None = _sentinel) -> None: # type: ignore388 """Pops the request context and unbinds it by doing that. This will389 also trigger the execution of functions registered by the390 :meth:`~flask.Flask.teardown_request` decorator.391 28 unmodified lines420 raise AssertionError(421 f"Popped wrong request context. ({ctx!r} instead of {self!r})"422 )423 422- def __enter__(self) -> "RequestContext":424+ def __enter__(self) -> RequestContext:425 self.push()426 return self427 428 def __exit__(429 self,428- exc_type: t.Optional[type],429- exc_value: t.Optional[BaseException],430- tb: t.Optional[TracebackType],430+ exc_type: type | None,431+ exc_value: BaseException | None,432+ tb: TracebackType | None,433 ) -> None:434 self.pop(exc_value)435 436 def __repr__(self) -> str:4 unmodified linesmodified:src/flask/debughelpers.py+2 added
1+from __future__ import annotations2+3 import typing as t4 5 from .app import Flask6 from .blueprints import Blueprint154 unmodified linesmodified:src/flask/globals.py+11 added-9 removed
1+from __future__ import annotations2+3 import typing as t4 from contextvars import ContextVar5 6 from werkzeug.local import LocalProxy12 unmodified lines19 self.name = name20 self.cv = cv21 22 @property21- def top(self) -> t.Optional[t.Any]:23+ def top(self) -> t.Any | None:24 import warnings25 26 warnings.warn(27 f"'_{self.name}_ctx_stack' is deprecated and will be removed in Flask 2.4."11 unmodified lines39 This typically means that you attempted to use functionality that needed40 the current application. To solve this, set up an application context41 with app.app_context(). See the documentation for more information.\42 """41-_cv_app: ContextVar["AppContext"] = ContextVar("flask.app_ctx")43+_cv_app: ContextVar[AppContext] = ContextVar("flask.app_ctx")44 __app_ctx_stack = _FakeStack("app", _cv_app)43-app_ctx: "AppContext" = LocalProxy( # type: ignore[assignment]45+app_ctx: AppContext = LocalProxy( # type: ignore[assignment]46 _cv_app, unbound_message=_no_app_msg47 )46-current_app: "Flask" = LocalProxy( # type: ignore[assignment]48+current_app: Flask = LocalProxy( # type: ignore[assignment]49 _cv_app, "app", unbound_message=_no_app_msg50 )49-g: "_AppCtxGlobals" = LocalProxy( # type: ignore[assignment]51+g: _AppCtxGlobals = LocalProxy( # type: ignore[assignment]52 _cv_app, "g", unbound_message=_no_app_msg53 )54 55 _no_req_msg = """\2 unmodified lines58 This typically means that you attempted to use functionality that needed59 an active HTTP request. Consult the documentation on testing for60 information about how to avoid this problem.\61 """60-_cv_request: ContextVar["RequestContext"] = ContextVar("flask.request_ctx")62+_cv_request: ContextVar[RequestContext] = ContextVar("flask.request_ctx")63 __request_ctx_stack = _FakeStack("request", _cv_request)62-request_ctx: "RequestContext" = LocalProxy( # type: ignore[assignment]64+request_ctx: RequestContext = LocalProxy( # type: ignore[assignment]65 _cv_request, unbound_message=_no_req_msg66 )65-request: "Request" = LocalProxy( # type: ignore[assignment]67+request: Request = LocalProxy( # type: ignore[assignment]68 _cv_request, "request", unbound_message=_no_req_msg69 )68-session: "SessionMixin" = LocalProxy( # type: ignore[assignment]70+session: SessionMixin = LocalProxy( # type: ignore[assignment]71 _cv_request, "session", unbound_message=_no_req_msg72 )73 74 22 unmodified linesmodified:src/flask/helpers.py+29 added-31 removed
1+from __future__ import annotations2+3 import os4 import pkgutil5 import socket6 import sys44 unmodified lines51 return val.lower() in ("0", "false", "no")52 53 54 def stream_with_context(53- generator_or_function: t.Union[54- t.Iterator[t.AnyStr], t.Callable[..., t.Iterator[t.AnyStr]]55- ]55+ generator_or_function: (56+ t.Iterator[t.AnyStr] | t.Callable[..., t.Iterator[t.AnyStr]]57+ )58 ) -> t.Iterator[t.AnyStr]:59 """Request contexts disappear when the response is started on the server.60 This is done for efficiency reasons and to make it less likely to encounter61 memory leaks with badly written WSGI middlewares. The downside is that if67 unmodified lines129 next(wrapped_g)130 return wrapped_g131 132 131-def make_response(*args: t.Any) -> "Response":133+def make_response(*args: t.Any) -> Response:134 """Sometimes it is necessary to set additional headers in a view. Because135 views do not have to return response objects but can return a value that136 is converted into a response object by Flask itself, it becomes tricky to137 add headers to it. This function can be called instead of using a return43 unmodified lines181 182 def url_for(183 endpoint: str,184 *,183- _anchor: t.Optional[str] = None,184- _method: t.Optional[str] = None,185- _scheme: t.Optional[str] = None,186- _external: t.Optional[bool] = None,185+ _anchor: str | None = None,186+ _method: str | None = None,187+ _scheme: str | None = None,188+ _external: bool | None = None,189 **values: t.Any,190 ) -> str:191 """Generate a URL to the given endpoint with the given values.192 40 unmodified lines233 )234 235 236 def redirect(235- location: str, code: int = 302, Response: t.Optional[t.Type["BaseResponse"]] = None236-) -> "BaseResponse":237+ location: str, code: int = 302, Response: type[BaseResponse] | None = None238+) -> BaseResponse:239 """Create a redirect response object.240 241 If :data:`~flask.current_app` is available, it will use its242 :meth:`~flask.Flask.redirect` method, otherwise it will use13 unmodified lines256 257 return _wz_redirect(location, code=code, Response=Response)258 259 258-def abort(259- code: t.Union[int, "BaseResponse"], *args: t.Any, **kwargs: t.Any260-) -> "te.NoReturn":260+def abort(code: int | BaseResponse, *args: t.Any, **kwargs: t.Any) -> te.NoReturn:261 """Raise an :exc:`~werkzeug.exceptions.HTTPException` for the given262 status code.263 264 If :data:`~flask.current_app` is available, it will call its72 unmodified lines337 338 339 def get_flashed_messages(340 with_categories: bool = False, category_filter: t.Iterable[str] = ()341-) -> t.Union[t.List[str], t.List[t.Tuple[str, str]]]:341+) -> list[str] | list[tuple[str, str]]:342 """Pulls all flashed messages from the session and returns them.343 Further calls in the same request to the function will return344 the same messages. By default just the messages are returned,345 but when `with_categories` is set to ``True``, the return value will31 unmodified lines377 return [x[1] for x in flashes]378 return flashes379 380 381-def _prepare_send_file_kwargs(**kwargs: t.Any) -> t.Dict[str, t.Any]:381+def _prepare_send_file_kwargs(**kwargs: t.Any) -> dict[str, t.Any]:382 if kwargs.get("max_age") is None:383 kwargs["max_age"] = current_app.get_send_file_max_age384 385 kwargs.update(5 unmodified lines391 return kwargs392 393 394 def send_file(395- path_or_file: t.Union[os.PathLike, str, t.BinaryIO],396- mimetype: t.Optional[str] = None,395+ path_or_file: os.PathLike | str | t.BinaryIO,396+ mimetype: str | None = None,397 as_attachment: bool = False,398- download_name: t.Optional[str] = None,398+ download_name: str | None = None,399 conditional: bool = True,400- etag: t.Union[bool, str] = True,401- last_modified: t.Optional[t.Union[datetime, int, float]] = None,402- max_age: t.Optional[403- t.Union[int, t.Callable[[t.Optional[str]], t.Optional[int]]]404- ] = None,405-) -> "Response":400+ etag: bool | str = True,401+ last_modified: datetime | int | float | None = None,402+ max_age: None | (int | t.Callable[[str | None], int | None]) = None,403+) -> Response:404 """Send the contents of a file to the client.405 406 The first argument can be a file path or a file-like object. Paths407 are preferred in most cases because Werkzeug can manage the file and109 unmodified lines517 )518 519 520 def send_from_directory(523- directory: t.Union[os.PathLike, str],524- path: t.Union[os.PathLike, str],521+ directory: os.PathLike | str,522+ path: os.PathLike | str,523 **kwargs: t.Any,526-) -> "Response":524+) -> Response:525 """Send a file from within a directory using :func:`send_file`.526 527 .. code-block:: python528 95 unmodified lines624 625 def __init__(626 self,627 fget: t.Callable[[t.Any], t.Any],630- name: t.Optional[str] = None,631- doc: t.Optional[str] = None,628+ name: str | None = None,629+ doc: str | None = None,630 ) -> None:631 import warnings632 633 warnings.warn(50 unmodified lines684 return False685 686 687 @lru_cache(maxsize=None)690-def _split_blueprint_path(name: str) -> t.List[str]:691- out: t.List[str] = [name]688+def _split_blueprint_path(name: str) -> list[str]:689+ out: list[str] = [name]690 691 if "." in name:692 out.extend(_split_blueprint_path(name.rpartition(".")[0]))693 1 unmodified linemodified:src/flask/logging.py+3 added-1 removed
1+from __future__ import annotations2+3 import logging4 import sys5 import typing as t6 44 unmodified lines51 logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")52 )53 54 53-def create_logger(app: "Flask") -> logging.Logger:55+def create_logger(app: Flask) -> logging.Logger:56 """Get the Flask app's logger and configure it if needed.57 58 The logger name will be the same as59 :attr:`app.import_name <flask.Flask.name>`.17 unmodified linesmodified:src/flask/scaffold.py+38 added-36 removed
1+from __future__ import annotations2+3 import importlib.util4 import os5 import pathlib6 import pkgutil64 unmodified lines71 .. versionadded:: 2.072 """73 74 name: str73- _static_folder: t.Optional[str] = None74- _static_url_path: t.Optional[str] = None75+ _static_folder: str | None = None76+ _static_url_path: str | None = None77 78 def __init__(79 self,80 import_name: str,79- static_folder: t.Optional[t.Union[str, os.PathLike]] = None,80- static_url_path: t.Optional[str] = None,81- template_folder: t.Optional[t.Union[str, os.PathLike]] = None,82- root_path: t.Optional[str] = None,81+ static_folder: str | os.PathLike | None = None,82+ static_url_path: str | None = None,83+ template_folder: str | os.PathLike | None = None,84+ root_path: str | None = None,85 ):86 #: The name of the package or module that this object belongs87 #: to. Do not change this once it is set by the constructor.88 self.import_name = import_name24 unmodified lines113 #: To register a view function, use the :meth:`route` decorator.114 #:115 #: This data structure is internal. It should not be modified116 #: directly and its format may change at any time.115- self.view_functions: t.Dict[str, t.Callable] = {}117+ self.view_functions: dict[str, t.Callable] = {}118 119 #: A data structure of registered error handlers, in the format120 #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is121 #: the name of a blueprint the handlers are active for, or6 unmodified lines128 #: decorator.129 #:130 #: This data structure is internal. It should not be modified131 #: directly and its format may change at any time.130- self.error_handler_spec: t.Dict[132+ self.error_handler_spec: dict[133 ft.AppOrBlueprintKey,132- t.Dict[t.Optional[int], t.Dict[t.Type[Exception], ft.ErrorHandlerCallable]],134+ dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]],135 ] = defaultdict(lambda: defaultdict(dict))136 137 #: A data structure of functions to call at the beginning of138 #: each request, in the format ``{scope: [functions]}``. The4 unmodified lines143 #: decorator.144 #:145 #: This data structure is internal. It should not be modified146 #: directly and its format may change at any time.145- self.before_request_funcs: t.Dict[146- ft.AppOrBlueprintKey, t.List[ft.BeforeRequestCallable]147+ self.before_request_funcs: dict[148+ ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]149 ] = defaultdict(list)150 151 #: A data structure of functions to call at the end of each152 #: request, in the format ``{scope: [functions]}``. The4 unmodified lines157 #: decorator.158 #:159 #: This data structure is internal. It should not be modified160 #: directly and its format may change at any time.159- self.after_request_funcs: t.Dict[160- ft.AppOrBlueprintKey, t.List[ft.AfterRequestCallable]161+ self.after_request_funcs: dict[162+ ft.AppOrBlueprintKey, list[ft.AfterRequestCallable]163 ] = defaultdict(list)164 165 #: A data structure of functions to call at the end of each166 #: request even if an exception is raised, in the format5 unmodified lines172 #: decorator.173 #:174 #: This data structure is internal. It should not be modified175 #: directly and its format may change at any time.174- self.teardown_request_funcs: t.Dict[175- ft.AppOrBlueprintKey, t.List[ft.TeardownCallable]176+ self.teardown_request_funcs: dict[177+ ft.AppOrBlueprintKey, list[ft.TeardownCallable]178 ] = defaultdict(list)179 180 #: A data structure of functions to call to pass extra context181 #: values when rendering templates, in the format5 unmodified lines187 #: decorator.188 #:189 #: This data structure is internal. It should not be modified190 #: directly and its format may change at any time.189- self.template_context_processors: t.Dict[190- ft.AppOrBlueprintKey, t.List[ft.TemplateContextProcessorCallable]191+ self.template_context_processors: dict[192+ ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]193 ] = defaultdict(list, {None: [_default_template_ctx_processor]})194 195 #: A data structure of functions to call to modify the keyword196 #: arguments passed to the view function, in the format5 unmodified lines202 #: :meth:`url_value_preprocessor` decorator.203 #:204 #: This data structure is internal. It should not be modified205 #: directly and its format may change at any time.204- self.url_value_preprocessors: t.Dict[206+ self.url_value_preprocessors: dict[207 ft.AppOrBlueprintKey,206- t.List[ft.URLValuePreprocessorCallable],208+ list[ft.URLValuePreprocessorCallable],209 ] = defaultdict(list)210 211 #: A data structure of functions to call to modify the keyword212 #: arguments when generating URLs, in the format5 unmodified lines218 #: decorator.219 #:220 #: This data structure is internal. It should not be modified221 #: directly and its format may change at any time.220- self.url_default_functions: t.Dict[221- ft.AppOrBlueprintKey, t.List[ft.URLDefaultCallable]222+ self.url_default_functions: dict[223+ ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]224 ] = defaultdict(list)225 226 def __repr__(self) -> str:227 return f"<{type(self).__name__} {self.name!r}>"1 unmodified line229 def _check_setup_finished(self, f_name: str) -> None:230 raise NotImplementedError231 232 @property231- def static_folder(self) -> t.Optional[str]:233+ def static_folder(self) -> str | None:234 """The absolute path to the configured static folder. ``None``235 if no static folder is set.236 """237 if self._static_folder is not None:1 unmodified line239 else:240 return None241 242 @static_folder.setter241- def static_folder(self, value: t.Optional[t.Union[str, os.PathLike]]) -> None:243+ def static_folder(self, value: str | os.PathLike | None) -> None:244 if value is not None:245 value = os.fspath(value).rstrip(r"\/")246 247 self._static_folder = value6 unmodified lines254 """255 return self.static_folder is not None256 257 @property256- def static_url_path(self) -> t.Optional[str]:258+ def static_url_path(self) -> str | None:259 """The URL prefix that the static route will be accessible from.260 261 If it was not configured during init, it is derived from262 :attr:`static_folder`.7 unmodified lines270 271 return None272 273 @static_url_path.setter272- def static_url_path(self, value: t.Optional[str]) -> None:274+ def static_url_path(self, value: str | None) -> None:275 if value is not None:276 value = value.rstrip("/")277 278 self._static_url_path = value279 278- def get_send_file_max_age(self, filename: t.Optional[str]) -> t.Optional[int]:280+ def get_send_file_max_age(self, filename: str | None) -> int | None:281 """Used by :func:`send_file` to determine the ``max_age`` cache282 value for a given file path if it wasn't passed.283 284 By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from15 unmodified lines300 return int(value.total_seconds())301 302 return value303 302- def send_static_file(self, filename: str) -> "Response":304+ def send_static_file(self, filename: str) -> Response:305 """The view function used to serve files from306 :attr:`static_folder`. A route is automatically registered for307 this view at :attr:`static_url_path` if :attr:`static_folder` is308 set.10 unmodified lines319 t.cast(str, self.static_folder), filename, max_age=max_age320 )321 322 @cached_property321- def jinja_loader(self) -> t.Optional[FileSystemLoader]:323+ def jinja_loader(self) -> FileSystemLoader | None:324 """The Jinja loader for this object's templates. By default this325 is a class :class:`jinja2.loaders.FileSystemLoader` to326 :attr:`template_folder` if it is set.327 113 unmodified lines441 @setupmethod442 def add_url_rule(443 self,444 rule: str,443- endpoint: t.Optional[str] = None,444- view_func: t.Optional[ft.RouteCallable] = None,445- provide_automatic_options: t.Optional[bool] = None,445+ endpoint: str | None = None,446+ view_func: ft.RouteCallable | None = None,447+ provide_automatic_options: bool | None = None,448 **options: t.Any,449 ) -> None:450 """Register a rule for routing incoming requests and building451 URLs. The :meth:`route` decorator is a shortcut to call this217 unmodified lines669 return f670 671 @setupmethod672 def errorhandler(671- self, code_or_exception: t.Union[t.Type[Exception], int]673+ self, code_or_exception: type[Exception] | int674 ) -> t.Callable[[T_error_handler], T_error_handler]:675 """Register a function to handle errors by code or exception class.676 677 A decorator that is used to register a function given an36 unmodified lines714 715 @setupmethod716 def register_error_handler(717 self,716- code_or_exception: t.Union[t.Type[Exception], int],718+ code_or_exception: type[Exception] | int,719 f: ft.ErrorHandlerCallable,720 ) -> None:721 """Alternative error attach function to the :meth:`errorhandler`722 decorator that is more straightforward to use for non decorator5 unmodified lines728 self.error_handler_spec[None][code][exc_class] = f729 730 @staticmethod731 def _get_exc_class_and_code(730- exc_class_or_code: t.Union[t.Type[Exception], int]731- ) -> t.Tuple[t.Type[Exception], t.Optional[int]]:732+ exc_class_or_code: type[Exception] | int,733+ ) -> tuple[type[Exception], int | None]:734 """Get the exception class being handled. For HTTP status codes735 or ``HTTPException`` subclasses, return both the exception and736 status code.737 738 :param exc_class_or_code: Any exception class, or an HTTP status739 code as an integer.740 """739- exc_class: t.Type[Exception]741+ exc_class: type[Exception]742 743 if isinstance(exc_class_or_code, int):744 try:745 exc_class = default_exceptions[exc_class_or_code]178 unmodified linesmodified:src/flask/sessions.py+17 added-23 removed
1+from __future__ import annotations2+3 import hashlib4 import typing as t5 from collections.abc import MutableMapping6 from datetime import datetime86 unmodified lines93 available. Will still allow read-only access to the empty session94 but fail on setting.95 """96 95- def _fail(self, *args: t.Any, **kwargs: t.Any) -> "te.NoReturn":97+ def _fail(self, *args: t.Any, **kwargs: t.Any) -> te.NoReturn:98 raise RuntimeError(99 "The session is unavailable because no secret "100 "key was set. Set the secret_key on the "101 "application to something unique and secret."52 unmodified lines154 #:155 #: .. versionadded:: 0.10156 pickle_based = False157 156- def make_null_session(self, app: "Flask") -> NullSession:158+ def make_null_session(self, app: Flask) -> NullSession:159 """Creates a null session which acts as a replacement object if the160 real session support could not be loaded due to a configuration161 error. This mainly aids the user experience because the job of the162 null session is to still support lookup without complaining but12 unmodified lines175 by default.176 """177 return isinstance(obj, self.null_session_class)178 177- def get_cookie_name(self, app: "Flask") -> str:179+ def get_cookie_name(self, app: Flask) -> str:180 """The name of the session cookie. Uses``app.config["SESSION_COOKIE_NAME"]``."""181 return app.config["SESSION_COOKIE_NAME"]182 181- def get_cookie_domain(self, app: "Flask") -> t.Optional[str]:183+ def get_cookie_domain(self, app: Flask) -> str | None:184 """The value of the ``Domain`` parameter on the session cookie. If not set,185 browsers will only send the cookie to the exact domain it was set from.186 Otherwise, they will send it to any subdomain of the given value as well.187 4 unmodified lines192 """193 rv = app.config["SESSION_COOKIE_DOMAIN"]194 return rv if rv else None195 194- def get_cookie_path(self, app: "Flask") -> str:196+ def get_cookie_path(self, app: Flask) -> str:197 """Returns the path for which the cookie should be valid. The198 default implementation uses the value from the ``SESSION_COOKIE_PATH``199 config var if it's set, and falls back to ``APPLICATION_ROOT`` or200 uses ``/`` if it's ``None``.201 """202 return app.config["SESSION_COOKIE_PATH"] or app.config["APPLICATION_ROOT"]203 202- def get_cookie_httponly(self, app: "Flask") -> bool:204+ def get_cookie_httponly(self, app: Flask) -> bool:205 """Returns True if the session cookie should be httponly. This206 currently just returns the value of the ``SESSION_COOKIE_HTTPONLY``207 config var.208 """209 return app.config["SESSION_COOKIE_HTTPONLY"]210 209- def get_cookie_secure(self, app: "Flask") -> bool:211+ def get_cookie_secure(self, app: Flask) -> bool:212 """Returns True if the cookie should be secure. This currently213 just returns the value of the ``SESSION_COOKIE_SECURE`` setting.214 """215 return app.config["SESSION_COOKIE_SECURE"]216 215- def get_cookie_samesite(self, app: "Flask") -> str:217+ def get_cookie_samesite(self, app: Flask) -> str:218 """Return ``'Strict'`` or ``'Lax'`` if the cookie should use the219 ``SameSite`` attribute. This currently just returns the value of220 the :data:`SESSION_COOKIE_SAMESITE` setting.221 """222 return app.config["SESSION_COOKIE_SAMESITE"]223 222- def get_expiration_time(223- self, app: "Flask", session: SessionMixin224- ) -> t.Optional[datetime]:224+ def get_expiration_time(self, app: Flask, session: SessionMixin) -> datetime | None:225 """A helper method that returns an expiration date for the session226 or ``None`` if the session is linked to the browser session. The227 default implementation returns now + the permanent session228 lifetime configured on the application.1 unmodified line230 if session.permanent:231 return datetime.now(timezone.utc) + app.permanent_session_lifetime232 return None233 234- def should_set_cookie(self, app: "Flask", session: SessionMixin) -> bool:234+ def should_set_cookie(self, app: Flask, session: SessionMixin) -> bool:235 """Used by session backends to determine if a ``Set-Cookie`` header236 should be set for this session cookie for this response. If the session237 has been modified, the cookie is set. If the session is permanent and238 the ``SESSION_REFRESH_EACH_REQUEST`` config is true, the cookie is7 unmodified lines246 return session.modified or (247 session.permanent and app.config["SESSION_REFRESH_EACH_REQUEST"]248 )249 250- def open_session(251- self, app: "Flask", request: "Request"252- ) -> t.Optional[SessionMixin]:250+ def open_session(self, app: Flask, request: Request) -> SessionMixin | None:251 """This is called at the beginning of each request, after252 pushing the request context, before matching the URL.253 254 This must return an object which implements a dictionary-like6 unmodified lines261 """262 raise NotImplementedError()263 264 def save_session(267- self, app: "Flask", session: SessionMixin, response: "Response"265+ self, app: Flask, session: SessionMixin, response: Response266 ) -> None:267 """This is called at the end of each request, after generating268 a response, before removing the request context. It is skipped269 if :meth:`is_null_session` returns ``True``.22 unmodified lines292 #: such as datetime objects or tuples.293 serializer = session_json_serializer294 session_class = SecureCookieSession295 298- def get_signing_serializer(299- self, app: "Flask"300- ) -> t.Optional[URLSafeTimedSerializer]:296+ def get_signing_serializer(self, app: Flask) -> URLSafeTimedSerializer | None:297 if not app.secret_key:298 return None299 signer_kwargs = dict(300 key_derivation=self.key_derivation, digest_method=self.digest_method4 unmodified lines305 serializer=self.serializer,306 signer_kwargs=signer_kwargs,307 )308 313- def open_session(314- self, app: "Flask", request: "Request"315- ) -> t.Optional[SecureCookieSession]:309+ def open_session(self, app: Flask, request: Request) -> SecureCookieSession | None:310 s = self.get_signing_serializer(app)311 if s is None:312 return None313 val = request.cookies.get(self.get_cookie_name(app))6 unmodified lines320 except BadSignature:321 return self.session_class()322 323 def save_session(330- self, app: "Flask", session: SessionMixin, response: "Response"324+ self, app: Flask, session: SessionMixin, response: Response325 ) -> None:326 name = self.get_cookie_name(app)327 domain = self.get_cookie_domain(app)328 path = self.get_cookie_path(app)38 unmodified linesmodified:src/flask/templating.py+17 added-17 removed
1+from __future__ import annotations2+3 import typing as t4 5 from jinja2 import BaseLoader6 from jinja2 import Environment as BaseEnvironment12 unmodified lines19 from .app import Flask20 from .scaffold import Scaffold21 22 21-def _default_template_ctx_processor() -> t.Dict[str, t.Any]:23+def _default_template_ctx_processor() -> dict[str, t.Any]:24 """Default template context processor. Injects `request`,25 `session` and `g`.26 """27 appctx = _cv_app.get(None)28 reqctx = _cv_request.get(None)27- rv: t.Dict[str, t.Any] = {}29+ rv: dict[str, t.Any] = {}30 if appctx is not None:31 rv["g"] = appctx.g32 if reqctx is not None:33 rv["request"] = reqctx.request6 unmodified lines40 knowledge of how Flask's blueprint works so that it can prepend the41 name of the blueprint to referenced templates if necessary.42 """43 42- def __init__(self, app: "Flask", **options: t.Any) -> None:44+ def __init__(self, app: Flask, **options: t.Any) -> None:45 if "loader" not in options:46 options["loader"] = app.create_global_jinja_loader()47 BaseEnvironment.__init__(self, **options)48 self.app = app3 unmodified lines52 """A loader that looks for templates in the application and all53 the blueprint folders.54 """55 54- def __init__(self, app: "Flask") -> None:56+ def __init__(self, app: Flask) -> None:57 self.app = app58 59 def get_source( # type: ignore60 self, environment: Environment, template: str59- ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable]]:61+ ) -> tuple[str, str | None, t.Callable | None]:62 if self.app.config["EXPLAIN_TEMPLATE_LOADING"]:63 return self._get_source_explained(environment, template)64 return self._get_source_fast(environment, template)65 66 def _get_source_explained(67 self, environment: Environment, template: str66- ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable]]:68+ ) -> tuple[str, str | None, t.Callable | None]:69 attempts = []68- rv: t.Optional[t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]]69- trv: t.Optional[70- t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]71- ] = None70+ rv: tuple[str, str | None, t.Callable[[], bool] | None] | None71+ trv: None | (tuple[str, str | None, t.Callable[[], bool] | None]) = None72 73 for srcobj, loader in self._iter_loaders(template):74 try:75 rv = loader.get_source(environment, template)12 unmodified lines88 raise TemplateNotFound(template)89 90 def _get_source_fast(91 self, environment: Environment, template: str92- ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable]]:92+ ) -> tuple[str, str | None, t.Callable | None]:93 for _srcobj, loader in self._iter_loaders(template):94 try:95 return loader.get_source(environment, template)96 except TemplateNotFound:1 unmodified line98 raise TemplateNotFound(template)99 100 def _iter_loaders(101 self, template: str102- ) -> t.Generator[t.Tuple["Scaffold", BaseLoader], None, None]:102+ ) -> t.Generator[tuple[Scaffold, BaseLoader], None, None]:103 loader = self.app.jinja_loader104 if loader is not None:105 yield self.app, loader106 1 unmodified line108 loader = blueprint.jinja_loader109 if loader is not None:110 yield blueprint, loader111 112- def list_templates(self) -> t.List[str]:112+ def list_templates(self) -> list[str]:113 result = set()114 loader = self.app.jinja_loader115 if loader is not None:116 result.update(loader.list_templates())6 unmodified lines123 124 return list(result)125 126 127-def _render(app: "Flask", template: Template, context: t.Dict[str, t.Any]) -> str:127+def _render(app: Flask, template: Template, context: dict[str, t.Any]) -> str:128 app.update_template_context(context)129 before_render_template.send(130 app, _async_wrapper=app.ensure_sync, template=template, context=context131 )4 unmodified lines136 return rv137 138 139 def render_template(140- template_name_or_list: t.Union[str, Template, t.List[t.Union[str, Template]]],140+ template_name_or_list: str | Template | list[str | Template],141 **context: t.Any,142 ) -> str:143 """Render a template by name with the given context.144 18 unmodified lines163 return _render(app, template, context)164 165 166 def _stream(167- app: "Flask", template: Template, context: t.Dict[str, t.Any]167+ app: Flask, template: Template, context: dict[str, t.Any]168 ) -> t.Iterator[str]:169 app.update_template_context(context)170 before_render_template.send(171 app, _async_wrapper=app.ensure_sync, template=template, context=context14 unmodified lines186 return rv187 188 189 def stream_template(190- template_name_or_list: t.Union[str, Template, t.List[t.Union[str, Template]]],190+ template_name_or_list: str | Template | list[str | Template],191 **context: t.Any,192 ) -> t.Iterator[str]:193 """Render a template by name with the given context as a stream.194 This returns an iterator of strings, which can be used as a26 unmodified linesmodified:src/flask/testing.py+14 added-12 removed
1+from __future__ import annotations2+3 import typing as t4 from contextlib import contextmanager5 from contextlib import ExitStack6 from copy import copy37 unmodified lines44 """45 46 def __init__(47 self,46- app: "Flask",48+ app: Flask,49 path: str = "/",48- base_url: t.Optional[str] = None,49- subdomain: t.Optional[str] = None,50- url_scheme: t.Optional[str] = None,50+ base_url: str | None = None,51+ subdomain: str | None = None,52+ url_scheme: str | None = None,53 *args: t.Any,54 **kwargs: t.Any,55 ) -> None:56 assert not (base_url or subdomain or url_scheme) or (48 unmodified lines105 106 Basic usage is outlined in the :doc:`/testing` chapter.107 """108 107- application: "Flask"109+ application: Flask110 111 def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:112 super().__init__(*args, **kwargs)113 self.preserve_context = False112- self._new_contexts: t.List[t.ContextManager[t.Any]] = []114+ self._new_contexts: list[t.ContextManager[t.Any]] = []115 self._context_stack = ExitStack()116 self.environ_base = {117 "REMOTE_ADDR": "127.0.0.1",118 "HTTP_USER_AGENT": f"werkzeug/{werkzeug.__version__}",81 unmodified lines200 *args: t.Any,201 buffered: bool = False,202 follow_redirects: bool = False,203 **kwargs: t.Any,202- ) -> "TestResponse":204+ ) -> TestResponse:205 if args and isinstance(206 args[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest)207 ):208 if isinstance(args[0], werkzeug.test.EnvironBuilder):30 unmodified lines239 self._context_stack.enter_context(cm)240 241 return response242 241- def __enter__(self) -> "FlaskClient":243+ def __enter__(self) -> FlaskClient:244 if self.preserve_context:245 raise RuntimeError("Cannot nest client invocations")246 self.preserve_context = True247 return self248 249 def __exit__(250 self,249- exc_type: t.Optional[type],250- exc_value: t.Optional[BaseException],251- tb: t.Optional[TracebackType],251+ exc_type: type | None,252+ exc_value: BaseException | None,253+ tb: TracebackType | None,254 ) -> None:255 self.preserve_context = False256 self._context_stack.close()257 3 unmodified lines261 CLI commands. Typically created using262 :meth:`~flask.Flask.test_cli_runner`. See :ref:`testing-cli`.263 """264 263- def __init__(self, app: "Flask", **kwargs: t.Any) -> None:265+ def __init__(self, app: Flask, **kwargs: t.Any) -> None:266 self.app = app267 super().__init__(**kwargs)268 269 def invoke( # type: ignore23 unmodified linesmodified:src/flask/typing.py+2 added
1+from __future__ import annotations2+3 import typing as t4 5 if t.TYPE_CHECKING: # pragma: no cover6 from _typeshed.wsgi import WSGIApplication # noqa: F40176 unmodified linesmodified:src/flask/views.py+5 added-3 removed
1+from __future__ import annotations2+3 import typing as t4 5 from . import typing as ft6 from .globals import current_app39 unmodified lines46 47 #: The methods this view is registered for. Uses the same default48 #: (``["GET", "HEAD", "OPTIONS"]``) as ``route`` and49 #: ``add_url_rule`` by default.48- methods: t.ClassVar[t.Optional[t.Collection[str]]] = None50+ methods: t.ClassVar[t.Collection[str] | None] = None51 52 #: Control whether the ``OPTIONS`` method is handled automatically.53 #: Uses the same default (``True``) as ``route`` and54 #: ``add_url_rule`` by default.53- provide_automatic_options: t.ClassVar[t.Optional[bool]] = None55+ provide_automatic_options: t.ClassVar[bool | None] = None56 57 #: A list of decorators to apply, in order, to the generated view58 #: function. Remember that ``@decorator`` syntax is applied bottom59 #: to top, so the first decorator in the list would be the bottom60 #: decorator.61 #:62 #: .. versionadded:: 0.861- decorators: t.ClassVar[t.List[t.Callable]] = []63+ decorators: t.ClassVar[list[t.Callable]] = []64 65 #: Create a new instance of this view class for every request by66 #: default. If a view subclass sets this to ``False``, the same67 #: instance is used for every request.123 unmodified linesmodified:src/flask/wrappers.py+11 added-9 removed
1+from __future__ import annotations2+3 import typing as t4 5 from werkzeug.exceptions import BadRequest6 from werkzeug.wrappers import Request as RequestBase31 unmodified lines38 #: :exc:`~werkzeug.exceptions.MethodNotAllowed`)39 #: because the request was never internally bound.40 #:41 #: .. versionadded:: 0.640- url_rule: t.Optional["Rule"] = None42+ url_rule: Rule | None = None43 44 #: A dict of view arguments that matched the request. If an exception45 #: happened when matching, this will be ``None``.44- view_args: t.Optional[t.Dict[str, t.Any]] = None46+ view_args: dict[str, t.Any] | None = None47 48 #: If matching the URL failed, this is the exception that will be49 #: raised / was raised as part of the request handling. This is50 #: usually a :exc:`~werkzeug.exceptions.NotFound` exception or51 #: something similar.50- routing_exception: t.Optional[Exception] = None52+ routing_exception: Exception | None = None53 54 @property53- def max_content_length(self) -> t.Optional[int]: # type: ignore55+ def max_content_length(self) -> int | None: # type: ignore56 """Read-only view of the ``MAX_CONTENT_LENGTH`` config key."""57 if current_app:58 return current_app.config["MAX_CONTENT_LENGTH"]59 else:60 return None61 62 @property61- def endpoint(self) -> t.Optional[str]:63+ def endpoint(self) -> str | None:64 """The endpoint that matched the request URL.65 66 This will be ``None`` if matching failed or has not been67 performed yet.6 unmodified lines74 75 return None76 77 @property76- def blueprint(self) -> t.Optional[str]:78+ def blueprint(self) -> str | None:79 """The registered name of the current blueprint.80 81 This will be ``None`` if the endpoint is not part of a82 blueprint, or if URL matching failed or has not been performed10 unmodified lines93 94 return None95 96 @property95- def blueprints(self) -> t.List[str]:97+ def blueprints(self) -> list[str]:98 """The registered names of the current blueprint upwards through99 parent blueprints.100 101 This will be an empty list if there is no current blueprint, or22 unmodified lines124 from .debughelpers import attach_enctype_error_multidict125 126 attach_enctype_error_multidict(self)127 126- def on_json_loading_failed(self, e: t.Optional[ValueError]) -> t.Any:128+ def on_json_loading_failed(self, e: ValueError | None) -> t.Any:129 try:130 return super().on_json_loading_failed(e)131 except BadRequest as e:132 if current_app and current_app.debug:19 unmodified lines152 153 Added :attr:`max_cookie_size`.154 """155 154- default_mimetype: t.Optional[str] = "text/html"156+ default_mimetype: str | None = "text/html"157 158 json_module = json159 160 autocorrect_location_header = False13 unmodified linesmodified:CHANGES.rst+1 added
44 unmodified lines45 a subdomain match. Warnings about ``localhost`` and IP addresses are also removed.46 :issue:`5051`47 - The ``routes`` command shows each rule's ``subdomain`` or ``host`` when domain48 matching is in use. :issue:`5004`49+- Use postponed evaluation of annotations. :pr:`5071`50 51 52 Version 2.2.453 -------------1423 unmodified lines