Skip to content
Myr

add __future__ annotations

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

authored by David Lord · committed by David Lord · parent cfa863c · 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

19 files+277 added−262 removed

modified:src/flask/json/provider.py+2 added-2 removed
70 unmodified lines
71 """72 return self.loads(fp.read(), **kwargs)7374 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 lines
203 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] = {}208209 if (self.compact is None and self._app.debug) or self.compact is False:210 dump_args.setdefault("indent", 2)211 else:
5 unmodified lines
modified:src/flask/json/tag.py+10 added-8 removed
38 unmodified lines
39 return OrderedDict(value)4041 app.session_interface.serializer.register(TagOrderedDict, index=0)42"""43from __future__ import annotations4445import typing as t46from base64 import b64decode47from base64 import b64encode48from datetime import datetime
13 unmodified lines
62 __slots__ = ("serializer",)6364 #: 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 = None6766 def __init__(self, serializer: "TaggedJSONSerializer") -> None:68 def __init__(self, serializer: TaggedJSONSerializer) -> None:69 """Create a tagger for the given serializer."""70 self.serializer = serializer7172 def check(self, value: t.Any) -> bool:
172 unmodified lines
245 TagDateTime,246 ]247248 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] = []251252 for cls in self.default_tags:253 self.register(cls)254255 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.262263 :param tag_class: tag class to register. Will be instantiated with this
20 unmodified lines
284 self.order.append(tag)285 else:286 self.order.insert(index, tag)287286 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)293294 return value295294 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 lines
modified:src/flask/app.py+54 added-56 removed
1from __future__ import annotations23import functools4import inspect5import logging6import os
89 unmodified lines
9697 return inspect.iscoroutinefunction(func)989998def _make_timedelta(value: t.Union[timedelta, int, None]) -> t.Optional[timedelta]:100def _make_timedelta(value: timedelta | int | None) -> timedelta | None:101 if value is None or isinstance(value, timedelta):102 return value103104 return timedelta(seconds=value)
176 unmodified lines
281 permanent_session_lifetime = ConfigAttribute(282 "PERMANENT_SESSION_LIFETIME", get_converter=_make_timedelta283 )284283 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 lines
349 #: 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 = None354355 #: 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 = None362363 #: the session interface to use. By default an instance of364 #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.365 #:
2 unmodified lines
368369 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 lines
436 #: 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 ] = []443444 #: 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] = []451452 #: 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] = []457458 #: 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] = {}465466 #: 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 lines
735736 :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,)740741 # A template may be rendered outside a request context.742 if request:743 names = chain(names, reversed(request.blueprints))
42 unmodified lines
786 self.jinja_env.auto_reload = value787788 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 lines
907 # reset normally. This makes it possible to restart the server908 # without reloader and that stuff from an interactive shell.909 self._got_first_request = False910909 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`.914915 Note that if you are testing for assertions or exceptions in your
49 unmodified lines
965 return cls( # type: ignore966 self, self.response_class, use_cookies=use_cookies, **kwargs967 )968967 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`.972973 Returns an instance of :attr:`test_cli_runner_class`, by default
9 unmodified lines
983984 return cls(self, **kwargs) # type: ignore985986 @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 lines
1010 .. versionadded:: 0.71011 """1012 blueprint.register(self, options)10131012 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.10161017 .. versionadded:: 0.111018 """
2 unmodified lines
1021 @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: ignore
46 unmodified lines
1078 self.view_functions[endpoint] = view_func10791080 @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 lines
1100 return decorator11011102 @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 lines
1112 self.jinja_env.filters[name or f.__name__] = f11131114 @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 lines
1141 return decorator11421143 @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 lines
1155 self.jinja_env.tests[name or f.__name__] = f11561157 @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 lines
1179 return decorator11801181 @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 lines
1236 """1237 self.shell_context_processors.append(f)1238 return f12391238 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 lines
1261 return None12621263 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 lines
1331 return False13321333 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 either
65 unmodified lines
14051406 raise e14071408 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)14121413 if handler is not None:
2 unmodified lines
1416 return self.finalize_request(server_error, from_error_handler=True)14171418 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 the
4 unmodified lines
1429 self.logger.error(1430 f"Exception on {request.path} [{request.method}]", exc_info=exc_info1431 )14321433 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.14351436 In debug mode, intercept a routing redirect and replace it with1437 an error if the body will be discarded.
41 unmodified lines
1479 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)14851486 def full_dispatch_request(self) -> Response:1487 """Dispatches the request and on top of that performs request
14 unmodified lines
1502 return self.finalize_request(rv)15031504 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 the
33 unmodified lines
1544 rv = self.response_class()1545 rv.allow.update(methods)1546 return rv15471548 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 lines
1595 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 lines
1870 rv.headers.update(headers) # type: ignore[arg-type]18711872 return rv18731874 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 lines
1917 automatically called on URL building.19181919 .. versionadded:: 0.71920 """1923 names: t.Iterable[t.Optional[str]] = (None,)1921 names: t.Iterable[str | None] = (None,)19221923 # url_for may be called outside a request context, parse the1924 # passed endpoint instead of using request.blueprints.1925 if "." in endpoint:
6 unmodified lines
1932 for func in self.url_default_functions[name]:1933 func(endpoint, values)19341935 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 error
24 unmodified lines
1965 raise19661967 raise error19681971 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 lines
20212022 return response20232024 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 lines
20542055 request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)20562057 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.20612062 When handling a request, the application context is popped
134 unmodified lines
2197 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 lines
modified:src/flask/blueprints.py+29 added-27 removed
1from __future__ import annotations23import os4import typing as t5from collections import defaultdict6from functools import update_wrapper
32 unmodified lines
39 """4041 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 application
37 unmodified lines
8687 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 the
78 unmodified lines
174 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 lines
200201 self.name = name202 self.url_prefix = url_prefix203 self.subdomain = subdomain202 self.deferred_functions: t.List[DeferredSetupFunction] = []204 self.deferred_functions: list[DeferredSetupFunction] = []205206 if url_defaults is None:207 url_defaults = {}208209 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]] = []212213 def _check_setup_finished(self, f_name: str) -> None:214 if self._got_registered_once:215 raise AssertionError(
27 unmodified lines
243244 self.record(update_wrapper(wrapper, func))245246 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)254255 @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 lines
269 if blueprint is self:270 raise ValueError("Cannot register a blueprint on itself")271 self._blueprints.append((blueprint, options))272271 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 lines
409 @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 lines
438 )439440 @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 lines
455 return decorator456457 @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 lines
472 self.record_once(register_template)473474 @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 lines
491 return decorator492493 @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 lines
510 self.record_once(register_template)511512 @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 lines
529 return decorator530531 @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 lines
590 return f591592 @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 lines
modified:src/flask/cli.py+1 added-1 removed
283 unmodified lines
284 #: 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 = None291292 def load_app(self) -> Flask:
775 unmodified lines
modified:src/flask/config.py+8 added-6 removed
1from __future__ import annotations23import errno4import json5import os6import types
4 unmodified lines
1112class ConfigAttribute:13 """Makes an attribute forward to the config"""1413 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_converter1819 def __get__(self, obj: t.Any, owner: t.Any = None) -> t.Any:
51 unmodified lines
71 the application's :attr:`~flask.Flask.root_path`.72 :param defaults: an optional dictionary of default values73 """7473 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_path7879 def from_envvar(self, variable_name: str, silent: bool = False) -> bool:
112 unmodified lines
192 raise193 self.from_object(d)194 return True195194 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:199200 - a string: in this case the object with that name will be imported
78 unmodified lines
279280 return self.from_mapping(obj)281282 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.287288 :return: Always returns ``True``.289290 .. 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 lines
299 return True300301 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::306307 app.config['IMAGE_STORE_TYPE'] = 'fs'
38 unmodified lines
modified:src/flask/ctx.py+23 added-21 removed
1from __future__ import annotations23import contextvars4import sys5import typing as t6from functools import update_wrapper
54 unmodified lines
61 del self.__dict__[name]62 except KeyError:63 raise AttributeError(name) from None6463 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`.6869 :param name: Name of attribute to get.
164 unmodified lines
234 one is not already active. An app context is also pushed when235 running CLI commands.236 """237236 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] = []243244 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)248247 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 lines
263 )264265 appcontext_popped.send(self.app, _async_wrapper=self.app.ensure_sync)266265 def __enter__(self) -> "AppContext":267 def __enter__(self) -> AppContext:268 self.push()269 return self270271 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)278279
20 unmodified lines
300 """301302 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 lines
315 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] = []325324 self._cv_tokens: t.List[t.Tuple[contextvars.Token, t.Optional[AppContext]]] = []326 self._cv_tokens: list[tuple[contextvars.Token, AppContext | None]] = []327326 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 the
50 unmodified lines
383 # session is available in custom URL converters.384 if self.url_adapter is not None:385 self.match_request()386385 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 lines
420 raise AssertionError(421 f"Popped wrong request context. ({ctx!r} instead of {self!r})"422 )423422 def __enter__(self) -> "RequestContext":424 def __enter__(self) -> RequestContext:425 self.push()426 return self427428 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)435436 def __repr__(self) -> str:
4 unmodified lines
modified:src/flask/debughelpers.py+2 added
1from __future__ import annotations23import typing as t45from .app import Flask6from .blueprints import Blueprint
154 unmodified lines
modified:src/flask/globals.py+11 added-9 removed
1from __future__ import annotations23import typing as t4from contextvars import ContextVar56from werkzeug.local import LocalProxy
12 unmodified lines
19 self.name = name20 self.cv = cv2122 @property21 def top(self) -> t.Optional[t.Any]:23 def top(self) -> t.Any | None:24 import warnings2526 warnings.warn(27 f"'_{self.name}_ctx_stack' is deprecated and will be removed in Flask 2.4."
11 unmodified lines
39This typically means that you attempted to use functionality that needed40the current application. To solve this, set up an application context41with 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)43app_ctx: "AppContext" = LocalProxy( # type: ignore[assignment]45app_ctx: AppContext = LocalProxy( # type: ignore[assignment]46 _cv_app, unbound_message=_no_app_msg47)46current_app: "Flask" = LocalProxy( # type: ignore[assignment]48current_app: Flask = LocalProxy( # type: ignore[assignment]49 _cv_app, "app", unbound_message=_no_app_msg50)49g: "_AppCtxGlobals" = LocalProxy( # type: ignore[assignment]51g: _AppCtxGlobals = LocalProxy( # type: ignore[assignment]52 _cv_app, "g", unbound_message=_no_app_msg53)5455_no_req_msg = """\
2 unmodified lines
58This typically means that you attempted to use functionality that needed59an active HTTP request. Consult the documentation on testing for60information 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)62request_ctx: "RequestContext" = LocalProxy( # type: ignore[assignment]64request_ctx: RequestContext = LocalProxy( # type: ignore[assignment]65 _cv_request, unbound_message=_no_req_msg66)65request: "Request" = LocalProxy( # type: ignore[assignment]67request: Request = LocalProxy( # type: ignore[assignment]68 _cv_request, "request", unbound_message=_no_req_msg69)68session: "SessionMixin" = LocalProxy( # type: ignore[assignment]70session: SessionMixin = LocalProxy( # type: ignore[assignment]71 _cv_request, "session", unbound_message=_no_req_msg72)7374
22 unmodified lines
modified:src/flask/helpers.py+29 added-31 removed
1from __future__ import annotations23import os4import pkgutil5import socket6import sys
44 unmodified lines
51 return val.lower() in ("0", "false", "no")525354def 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 if
67 unmodified lines
129 next(wrapped_g)130 return wrapped_g131132131def make_response(*args: t.Any) -> "Response":133def 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 return
43 unmodified lines
181182def 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 lines
233 )234235236def 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.240241 If :data:`~flask.current_app` is available, it will use its242 :meth:`~flask.Flask.redirect` method, otherwise it will use
13 unmodified lines
256257 return _wz_redirect(location, code=code, Response=Response)258259258def abort(259 code: t.Union[int, "BaseResponse"], *args: t.Any, **kwargs: t.Any260) -> "te.NoReturn":260def abort(code: int | BaseResponse, *args: t.Any, **kwargs: t.Any) -> te.NoReturn:261 """Raise an :exc:`~werkzeug.exceptions.HTTPException` for the given262 status code.263264 If :data:`~flask.current_app` is available, it will call its
72 unmodified lines
337338339def 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 will
31 unmodified lines
377 return [x[1] for x in flashes]378 return flashes379380381def _prepare_send_file_kwargs(**kwargs: t.Any) -> t.Dict[str, t.Any]:381def _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_age384385 kwargs.update(
5 unmodified lines
391 return kwargs392393394def 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.405406 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 and
109 unmodified lines
517 )518519520def 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`.526527 .. code-block:: python528
95 unmodified lines
624625 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 warnings632633 warnings.warn(
50 unmodified lines
684 return False685686687@lru_cache(maxsize=None)690def _split_blueprint_path(name: str) -> t.List[str]:691 out: t.List[str] = [name]688def _split_blueprint_path(name: str) -> list[str]:689 out: list[str] = [name]690691 if "." in name:692 out.extend(_split_blueprint_path(name.rpartition(".")[0]))693
1 unmodified line
modified:src/flask/logging.py+3 added-1 removed
1from __future__ import annotations23import logging4import sys5import typing as t6
44 unmodified lines
51 logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")52)535453def create_logger(app: "Flask") -> logging.Logger:55def create_logger(app: Flask) -> logging.Logger:56 """Get the Flask app's logger and configure it if needed.5758 The logger name will be the same as59 :attr:`app.import_name <flask.Flask.name>`.
17 unmodified lines
modified:src/flask/scaffold.py+38 added-36 removed
1from __future__ import annotations23import importlib.util4import os5import pathlib6import pkgutil
64 unmodified lines
71 .. versionadded:: 2.072 """7374 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 = None7778 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_name
24 unmodified lines
113 #: 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] = {}118119 #: 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, or
6 unmodified lines
128 #: 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))136137 #: A data structure of functions to call at the beginning of138 #: each request, in the format ``{scope: [functions]}``. The
4 unmodified lines
143 #: 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)150151 #: A data structure of functions to call at the end of each152 #: request, in the format ``{scope: [functions]}``. The
4 unmodified lines
157 #: 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)164165 #: A data structure of functions to call at the end of each166 #: request even if an exception is raised, in the format
5 unmodified lines
172 #: 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)179180 #: A data structure of functions to call to pass extra context181 #: values when rendering templates, in the format
5 unmodified lines
187 #: 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]})194195 #: A data structure of functions to call to modify the keyword196 #: arguments passed to the view function, in the format
5 unmodified lines
202 #: :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)210211 #: A data structure of functions to call to modify the keyword212 #: arguments when generating URLs, in the format
5 unmodified lines
218 #: 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)225226 def __repr__(self) -> str:227 return f"<{type(self).__name__} {self.name!r}>"
1 unmodified line
229 def _check_setup_finished(self, f_name: str) -> None:230 raise NotImplementedError231232 @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 line
239 else:240 return None241242 @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"\/")246247 self._static_folder = value
6 unmodified lines
254 """255 return self.static_folder is not None256257 @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.260261 If it was not configured during init, it is derived from262 :attr:`static_folder`.
7 unmodified lines
270271 return None272273 @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("/")277278 self._static_url_path = value279278 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.283284 By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
15 unmodified lines
300 return int(value.total_seconds())301302 return value303302 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 lines
319 t.cast(str, self.static_folder), filename, max_age=max_age320 )321322 @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 lines
441 @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 this
217 unmodified lines
669 return f670671 @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.676677 A decorator that is used to register a function given an
36 unmodified lines
714715 @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 decorator
5 unmodified lines
728 self.error_handler_spec[None][code][exc_class] = f729730 @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.737738 :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]742743 if isinstance(exc_class_or_code, int):744 try:745 exc_class = default_exceptions[exc_class_or_code]
178 unmodified lines
modified:src/flask/sessions.py+17 added-23 removed
1from __future__ import annotations23import hashlib4import typing as t5from collections.abc import MutableMapping6from datetime import datetime
86 unmodified lines
93 available. Will still allow read-only access to the empty session94 but fail on setting.95 """9695 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 lines
154 #:155 #: .. versionadded:: 0.10156 pickle_based = False157156 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 but
12 unmodified lines
175 by default.176 """177 return isinstance(obj, self.null_session_class)178177 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"]182181 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 lines
192 """193 rv = app.config["SESSION_COOKIE_DOMAIN"]194 return rv if rv else None195194 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"]203202 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"]210209 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"]216215 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"]223222 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 line
230 if session.permanent:231 return datetime.now(timezone.utc) + app.permanent_session_lifetime232 return None233234 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 is
7 unmodified lines
246 return session.modified or (247 session.permanent and app.config["SESSION_REFRESH_EACH_REQUEST"]248 )249250 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.253254 This must return an object which implements a dictionary-like
6 unmodified lines
261 """262 raise NotImplementedError()263264 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 lines
292 #: such as datetime objects or tuples.293 serializer = session_json_serializer294 session_class = SecureCookieSession295298 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_method
4 unmodified lines
305 serializer=self.serializer,306 signer_kwargs=signer_kwargs,307 )308313 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 lines
320 except BadSignature:321 return self.session_class()322323 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 lines
modified:src/flask/templating.py+17 added-17 removed
1from __future__ import annotations23import typing as t45from jinja2 import BaseLoader6from jinja2 import Environment as BaseEnvironment
12 unmodified lines
19 from .app import Flask20 from .scaffold import Scaffold212221def _default_template_ctx_processor() -> t.Dict[str, t.Any]:23def _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.request
6 unmodified lines
40 knowledge of how Flask's blueprint works so that it can prepend the41 name of the blueprint to referenced templates if necessary.42 """4342 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 = app
3 unmodified lines
52 """A loader that looks for templates in the application and all53 the blueprint folders.54 """5554 def __init__(self, app: "Flask") -> None:56 def __init__(self, app: Flask) -> None:57 self.app = app5859 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)6566 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]) = None7273 for srcobj, loader in self._iter_loaders(template):74 try:75 rv = loader.get_source(environment, template)
12 unmodified lines
88 raise TemplateNotFound(template)8990 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 line
98 raise TemplateNotFound(template)99100 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 line
108 loader = blueprint.jinja_loader109 if loader is not None:110 yield blueprint, loader111112 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 lines
123124 return list(result)125126127def _render(app: "Flask", template: Template, context: t.Dict[str, t.Any]) -> str:127def _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 lines
136 return rv137138139def 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 lines
163 return _render(app, template, context)164165166def _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=context
14 unmodified lines
186 return rv187188189def 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 a
26 unmodified lines
modified:src/flask/testing.py+14 added-12 removed
1from __future__ import annotations23import typing as t4from contextlib import contextmanager5from contextlib import ExitStack6from copy import copy
37 unmodified lines
44 """4546 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 lines
105106 Basic usage is outlined in the :doc:`/testing` chapter.107 """108107 application: "Flask"109 application: Flask110111 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 lines
200 *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 lines
239 self._context_stack.enter_context(cm)240241 return response242241 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 self248249 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 lines
261 CLI commands. Typically created using262 :meth:`~flask.Flask.test_cli_runner`. See :ref:`testing-cli`.263 """264263 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)268269 def invoke( # type: ignore
23 unmodified lines
modified:src/flask/typing.py+2 added
1from __future__ import annotations23import typing as t45if t.TYPE_CHECKING: # pragma: no cover6 from _typeshed.wsgi import WSGIApplication # noqa: F401
76 unmodified lines
modified:src/flask/views.py+5 added-3 removed
1from __future__ import annotations23import typing as t45from . import typing as ft6from .globals import current_app
39 unmodified lines
4647 #: 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] = None5152 #: 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] = None5657 #: 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]] = []6465 #: 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 lines
modified:src/flask/wrappers.py+11 added-9 removed
1from __future__ import annotations23import typing as t45from werkzeug.exceptions import BadRequest6from werkzeug.wrappers import Request as RequestBase
31 unmodified lines
38 #: :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 = None4344 #: 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 = None4748 #: 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 = None5354 @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 None6162 @property61 def endpoint(self) -> t.Optional[str]:63 def endpoint(self) -> str | None:64 """The endpoint that matched the request URL.6566 This will be ``None`` if matching failed or has not been67 performed yet.
6 unmodified lines
7475 return None7677 @property76 def blueprint(self) -> t.Optional[str]:78 def blueprint(self) -> str | None:79 """The registered name of the current blueprint.8081 This will be ``None`` if the endpoint is not part of a82 blueprint, or if URL matching failed or has not been performed
10 unmodified lines
9394 return None9596 @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.100101 This will be an empty list if there is no current blueprint, or
22 unmodified lines
124 from .debughelpers import attach_enctype_error_multidict125126 attach_enctype_error_multidict(self)127126 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 lines
152153 Added :attr:`max_cookie_size`.154 """155154 default_mimetype: t.Optional[str] = "text/html"156 default_mimetype: str | None = "text/html"157158 json_module = json159160 autocorrect_location_header = False
13 unmodified lines
modified:CHANGES.rst+1 added
44 unmodified lines
45 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`505152Version 2.2.453-------------
1423 unmodified lines