Skip to content
Myr

Merge branch '3.0.x'

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 · parents 7b5e176, 233be7a · Browse files · 30 files+411 added−296 removed
This commit

State

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

Diff stats

30 files+411 added−296 removed

  • other:+411 added−296 removed

30 files+411 added−296 removed

modified:.github/workflows/lock.yaml+6 added-10 removed
modified:.github/workflows/publish.yaml+5 added-7 removed
modified:.github/workflows/tests.yaml+2 added-2 removed
modified:requirements/dev.txt+25 added-26 removed
2 unmodified lines
3# by the following command:4#5# pip-compile dev.in6#7alabaster==0.7.137alabaster==0.7.168 # via sphinx9asgiref==3.7.210 # via -r tests.in11babel==2.13.110 # via11 # -r tests.in12 # -r typing.in13babel==2.14.014 # via sphinx15build==1.0.316 # via pip-tools17cachetools==5.3.218 # via tox17certifi==2023.7.2219certifi==2023.11.1720 # via requests21cffi==1.16.022 # via cryptography23cfgv==3.4.0
7 unmodified lines
31colorama==0.4.632 # via tox33cryptography==41.0.734 # via -r typing.in33distlib==0.3.735distlib==0.3.836 # via virtualenv37docutils==0.18.138 # via39 # sphinx
1 unmodified line
41filelock==3.13.142 # via43 # tox44 # virtualenv43identify==2.5.3145identify==2.5.3346 # via pre-commit45idna==3.447idna==3.648 # via requests49imagesize==1.4.150 # via sphinx51iniconfig==2.0.052 # via pytest51jinja2==3.1.253jinja2==3.1.354 # via sphinx55markupsafe==2.1.356 # via jinja257mypy==1.8.0
13 unmodified lines
71pallets-sphinx-themes==2.1.172 # via -r docs.in73pip-tools==7.3.074 # via -r dev.in73platformdirs==3.11.075platformdirs==4.1.076 # via77 # tox78 # virtualenv79pluggy==1.3.0
3 unmodified lines
83pre-commit==3.6.084 # via -r dev.in85pycparser==2.2186 # via cffi85pygments==2.16.187pygments==2.17.288 # via89 # sphinx90 # sphinx-tabs91pyproject-api==1.6.1
2 unmodified lines
94 # via build95pytest==7.4.496 # via -r tests.in97python-dotenv==1.0.096 # via -r tests.in98 # via99 # -r tests.in100 # -r typing.in101pyyaml==6.0.1102 # via pre-commit103requests==2.31.0104 # via sphinx
4 unmodified lines
109 # -r docs.in110 # pallets-sphinx-themes111 # sphinx-issues112 # sphinx-tabs109 # sphinxcontrib-applehelp110 # sphinxcontrib-devhelp111 # sphinxcontrib-htmlhelp113 # sphinxcontrib-log-cabinet113 # sphinxcontrib-qthelp114 # sphinxcontrib-serializinghtml114sphinx-issues==3.0.1115 # via -r docs.in116sphinx-tabs==3.4.4117 # via -r docs.in119sphinxcontrib-applehelp==1.0.7118sphinxcontrib-applehelp==1.0.8119 # via sphinx121sphinxcontrib-devhelp==1.0.5120sphinxcontrib-devhelp==1.0.6121 # via sphinx123sphinxcontrib-htmlhelp==2.0.4122sphinxcontrib-htmlhelp==2.0.5123 # via sphinx124sphinxcontrib-jsmath==1.0.1125 # via sphinx126sphinxcontrib-log-cabinet==1.0.1127 # via -r docs.in129sphinxcontrib-qthelp==1.0.6128sphinxcontrib-qthelp==1.0.7129 # via sphinx131sphinxcontrib-serializinghtml==1.1.9130sphinxcontrib-serializinghtml==1.1.10131 # via sphinx133tox==4.11.4132tox==4.12.0133 # via -r dev.in134types-contextvars==2.4.7.3135 # via -r typing.in136types-dataclasses==0.6.6137 # via -r typing.in139typing-extensions==4.8.0138typing-extensions==4.9.0139 # via mypy141urllib3==2.0.7140urllib3==2.1.0141 # via requests143virtualenv==20.24.6142virtualenv==20.25.0143 # via144 # pre-commit145 # tox147wheel==0.41.3146wheel==0.42.0147 # via pip-tools148149# The following packages are considered to be unsafe in a requirements file:150# pip
1 unmodified line
modified:requirements/docs.txt+12 added-17 removed
2 unmodified lines
3# by the following command:4#5# pip-compile docs.in6#7alabaster==0.7.137alabaster==0.7.168 # via sphinx9babel==2.13.19babel==2.14.010 # via sphinx11certifi==2023.7.2211certifi==2023.11.1712 # via requests13charset-normalizer==3.3.214 # via requests15docutils==0.18.116 # via17 # sphinx18 # sphinx-tabs19idna==3.419idna==3.620 # via requests21imagesize==1.4.122 # via sphinx23jinja2==3.1.223jinja2==3.1.324 # via sphinx25markupsafe==2.1.326 # via jinja227packaging==23.2
1 unmodified line
29 # pallets-sphinx-themes30 # sphinx31pallets-sphinx-themes==2.1.132 # via -r docs.in33pygments==2.16.133pygments==2.17.234 # via35 # sphinx36 # sphinx-tabs37requests==2.31.0
5 unmodified lines
43 # -r docs.in44 # pallets-sphinx-themes45 # sphinx-issues46 # sphinx-tabs47 # sphinxcontrib-applehelp48 # sphinxcontrib-devhelp49 # sphinxcontrib-htmlhelp47 # sphinxcontrib-log-cabinet51 # sphinxcontrib-qthelp52 # sphinxcontrib-serializinghtml48sphinx-issues==3.0.149 # via -r docs.in50sphinx-tabs==3.4.451 # via -r docs.in57sphinxcontrib-applehelp==1.0.752sphinxcontrib-applehelp==1.0.853 # via sphinx59sphinxcontrib-devhelp==1.0.554sphinxcontrib-devhelp==1.0.655 # via sphinx61sphinxcontrib-htmlhelp==2.0.456sphinxcontrib-htmlhelp==2.0.557 # via sphinx58sphinxcontrib-jsmath==1.0.159 # via sphinx60sphinxcontrib-log-cabinet==1.0.161 # via -r docs.in67sphinxcontrib-qthelp==1.0.662sphinxcontrib-qthelp==1.0.763 # via sphinx69sphinxcontrib-serializinghtml==1.1.964sphinxcontrib-serializinghtml==1.1.1065 # via sphinx71urllib3==2.0.766urllib3==2.1.067 # via requests
modified:requirements/typing.in+2 added
1mypy2types-contextvars3types-dataclasses4asgiref5cryptography6python-dotenv
modified:requirements/typing.txt+5 added-1 removed
2 unmodified lines
3# by the following command:4#5# pip-compile typing.in6#7asgiref==3.7.28 # via -r typing.in9cffi==1.16.010 # via cryptography11cryptography==41.0.712 # via -r typing.in
2 unmodified lines
15mypy-extensions==1.0.016 # via mypy17pycparser==2.2118 # via cffi19python-dotenv==1.0.020 # via -r typing.in21types-contextvars==2.4.7.322 # via -r typing.in23types-dataclasses==0.6.624 # via -r typing.in21typing-extensions==4.8.025typing-extensions==4.9.026 # via mypy
modified:src/flask/json/__init__.py+1 added-1 removed
165 unmodified lines
166 security risk in ancient browsers. See :ref:`security-json`.167168 .. versionadded:: 0.2169 """170 return current_app.json.response(*args, **kwargs)170 return current_app.json.response(*args, **kwargs) # type: ignore[return-value]
modified:src/flask/json/provider.py+3 added-2 removed
9 unmodified lines
1011from werkzeug.http import http_date1213if t.TYPE_CHECKING: # pragma: no cover14 from werkzeug.sansio.response import Response1516 from ..sansio.app import App15 from ..wrappers import Response171819class JSONProvider:20 """A standard set of JSON operations for an application. Subclasses
14 unmodified lines
35 .. versionadded:: 2.236 """3738 def __init__(self, app: App) -> None:38 self._app = weakref.proxy(app)39 self._app: App = weakref.proxy(app)4041 def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:42 """Serialize data as JSON.43
172 unmodified lines
modified:src/flask/json/tag.py+18 added-6 removed
59 unmodified lines
60 """Base class for defining type tags for :class:`TaggedJSONSerializer`."""6162 __slots__ = ("serializer",)6364 #: The tag to mark the serialized object with. If ``None``, this tag is64 #: The tag to mark the serialized object with. If empty, this tag is65 #: only used as an intermediate step during tagging.66 key: str | None = None66 key: str = ""6768 def __init__(self, serializer: TaggedJSONSerializer) -> None:69 """Create a tagger for the given serializer."""70 self.serializer = serializer
11 unmodified lines
82 """Convert the JSON representation back to the correct type. The tag83 will already be removed."""84 raise NotImplementedError8586 def tag(self, value: t.Any) -> t.Any:86 def tag(self, value: t.Any) -> dict[str, t.Any]:87 """Convert the value to a valid JSON type and add the tag structure88 around it."""89 return {self.key: self.to_json(value)}90
182 unmodified lines
273 """274 tag = tag_class(self)275 key = tag.key276277 if key is not None:277 if key:278 if not force and key in self.tags:279 raise KeyError(f"Tag '{key}' is already registered.")280281 self.tags[key] = tag
2 unmodified lines
284 self.order.append(tag)285 else:286 self.order.insert(index, tag)287288 def tag(self, value: t.Any) -> dict[str, t.Any]:288 def tag(self, value: t.Any) -> 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)
11 unmodified lines
304 return value305306 return self.tags[key].to_python(value[key])307308 def _untag_scan(self, value: t.Any) -> t.Any:309 if isinstance(value, dict):310 # untag each item recursively311 value = {k: self._untag_scan(v) for k, v in value.items()}312 # untag the dict itself313 value = self.untag(value)314 elif isinstance(value, list):315 # untag each item recursively316 value = [self._untag_scan(item) for item in value]317318 return value319320 def dumps(self, value: t.Any) -> str:321 """Tag the value and dump it to a compact JSON string."""322 return dumps(self.tag(value), separators=(",", ":"))323324 def loads(self, value: str) -> t.Any:325 """Load data from a JSON string and deserialized any tagged objects."""314 return loads(value, object_hook=self.untag)326 return self._untag_scan(loads(value))
modified:src/flask/sansio/app.py+16 added-15 removed
203 unmodified lines
204 #: default it's implicitly enabled.205 #:206 #: This attribute can also be configured from the config with the207 #: ``TESTING`` configuration key. Defaults to ``False``.208 testing = ConfigAttribute("TESTING")208 testing = ConfigAttribute[bool]("TESTING")209210 #: If a secret key is set, cryptographic components can use this to211 #: sign cookies and other things. Set this to a complex random value212 #: when you want to use the secure cookie for instance.213 #:214 #: This attribute can also be configured from the config with the215 #: :data:`SECRET_KEY` configuration key. Defaults to ``None``.216 secret_key = ConfigAttribute("SECRET_KEY")216 secret_key = ConfigAttribute[t.Union[str, bytes, None]]("SECRET_KEY")217218 #: A :class:`~datetime.timedelta` which is used to set the expiration219 #: date of a permanent session. The default is 31 days which makes a220 #: permanent session survive for roughly one month.221 #:222 #: This attribute can also be configured from the config with the223 #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to224 #: ``timedelta(days=31)``225 permanent_session_lifetime = ConfigAttribute(226 "PERMANENT_SESSION_LIFETIME", get_converter=_make_timedelta225 permanent_session_lifetime = ConfigAttribute[timedelta](226 "PERMANENT_SESSION_LIFETIME",227 get_converter=_make_timedelta, # type: ignore[arg-type]228 )229230 json_provider_class: type[JSONProvider] = DefaultJSONProvider231 """A subclass of :class:`~flask.json.provider.JSONProvider`. An
15 unmodified lines
247 #: .. versionchanged:: 1.1.0248 #: This is a ``dict`` instead of an ``ImmutableDict`` to allow249 #: easier configuration.250 #:250 jinja_options: dict = {}251 jinja_options: dict[str, t.Any] = {}252253 #: The rule object to use for URL rules created. This is used by254 #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.255 #:
19 unmodified lines
275 #:276 #: .. versionadded:: 1.0277 test_cli_runner_class: type[FlaskCliRunner] | None = None278278 default_config: dict279 default_config: dict[str, t.Any]280 response_class: type[Response]281282 def __init__(283 self,284 import_name: str,285 static_url_path: str | None = None,285 static_folder: str | os.PathLike | None = "static",286 static_folder: str | os.PathLike[str] | None = "static",287 static_host: str | None = None,288 host_matching: bool = False,289 subdomain_matching: bool = False,289 template_folder: str | os.PathLike | None = "templates",290 template_folder: str | os.PathLike[str] | None = "templates",291 instance_path: str | None = None,292 instance_relative_config: bool = False,293 root_path: str | None = None,294 ):
89 unmodified lines
384 #: case of a "Flask-Foo" extension in `flask_foo`, the key would be385 #: ``'foo'``.386 #:387 #: .. versionadded:: 0.7387 self.extensions: dict = {}388 self.extensions: dict[str, t.Any] = {}389390 #: The :class:`~werkzeug.routing.Map` for this instance. You can use391 #: this to change the routing converters after the class was created392 #: but before any routes are connected. Example::
43 unmodified lines
436437 .. versionadded:: 0.8438 """439 if self.import_name == "__main__":439 fn = getattr(sys.modules["__main__"], "__file__", None)440 fn: str | None = getattr(sys.modules["__main__"], "__file__", None)441 if fn is None:442 return "__main__"443 return os.path.splitext(os.path.basename(fn))[0]444 return self.import_name
115 unmodified lines
560 **Do not enable debug mode when deploying in production.**561562 Default: ``False``563 """563 return self.config["DEBUG"]564 return self.config["DEBUG"] # type: ignore[no-any-return]565566 @debug.setter567 def debug(self, value: bool) -> None:568 self.config["DEBUG"] = value
81 unmodified lines
650651 # Add the required methods now.652 methods |= required_methods653653 rule = self.url_rule_class(rule, methods=methods, **options)654 rule.provide_automatic_options = provide_automatic_options # type: ignore654 rule_obj = self.url_rule_class(rule, methods=methods, **options)655 rule_obj.provide_automatic_options = provide_automatic_options # type: ignore[attr-defined]656656 self.url_map.add(rule)657 self.url_map.add(rule_obj)658 if view_func is not None:659 old_func = self.view_functions.get(endpoint)660 if old_func is not None and old_func != view_func:661 raise AssertionError(
249 unmodified lines
911 code=code,912 Response=self.response_class, # type: ignore[arg-type]913 )914914 def inject_url_defaults(self, endpoint: str, values: dict) -> None:915 def inject_url_defaults(self, endpoint: str, values: dict[str, t.Any]) -> None:916 """Injects the URL defaults for the given endpoint directly into917 the values dictionary passed. This is used internally and918 automatically called on URL building.919
49 unmodified lines
modified:src/flask/sansio/blueprints.py+20 added-14 removed
12 unmodified lines
1314if t.TYPE_CHECKING: # pragma: no cover15 from .app import App1617DeferredSetupFunction = t.Callable[["BlueprintSetupState"], t.Callable]18T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable)17DeferredSetupFunction = t.Callable[["BlueprintSetupState"], None]18T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable[t.Any])19T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable)20T_error_handler = t.TypeVar("T_error_handler", bound=ft.ErrorHandlerCallable)21T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)22T_template_context_processor = t.TypeVar(
64 unmodified lines
87 def add_url_rule(88 self,89 rule: str,90 endpoint: str | None = None,91 view_func: t.Callable | None = None,91 view_func: ft.RouteCallable | 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,178 static_folder: str | os.PathLike | None = None,178 static_folder: str | os.PathLike[str] | None = None,179 static_url_path: str | None = None,180 template_folder: str | os.PathLike | None = None,180 template_folder: str | os.PathLike[str] | None = None,181 url_prefix: str | None = None,182 subdomain: str | None = None,183 url_defaults: dict | None = None,183 url_defaults: dict[str, t.Any] | None = None,184 root_path: str | None = None,185 cli_group: str | None = _sentinel, # type: ignore185 cli_group: str | None = _sentinel, # type: ignore[assignment]186 ):187 super().__init__(188 import_name=import_name,189 static_folder=static_folder,
17 unmodified lines
207 url_defaults = {}208209 self.url_values_defaults = url_defaults210 self.cli_group = cli_group211 self._blueprints: list[tuple[Blueprint, dict]] = []211 self._blueprints: list[tuple[Blueprint, dict[str, t.Any]]] = []212213 def _check_setup_finished(self, f_name: str) -> None:214 if self._got_registered_once:215 raise AssertionError(
4 unmodified lines
220 " the blueprint are done before registering it."221 )222223 @setupmethod224 def record(self, func: t.Callable) -> None:224 def record(self, func: DeferredSetupFunction) -> None:225 """Registers a function that is called when the blueprint is226 registered on the application. This function is called with the227 state as argument as returned by the :meth:`make_setup_state`228 method.229 """230 self.deferred_functions.append(func)231232 @setupmethod233 def record_once(self, func: t.Callable) -> None:233 def record_once(self, func: DeferredSetupFunction) -> None:234 """Works like :meth:`record` but wraps the function in another235 function that will ensure the function is only called once. If the236 blueprint is registered a second time on the application, the237 function passed is not called.
5 unmodified lines
243244 self.record(update_wrapper(wrapper, func))245246 def make_setup_state(247 self, app: App, options: dict, first_registration: bool = False247 self, app: App, options: dict[str, t.Any], 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.
17 unmodified lines
269 if blueprint is self:270 raise ValueError("Cannot register a blueprint on itself")271 self._blueprints.append((blueprint, options))272273 def register(self, app: App, options: dict) -> None:273 def register(self, app: App, options: dict[str, t.Any]) -> 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.
98 unmodified lines
376 bp_options["name_prefix"] = name377 blueprint.register(app, bp_options)378379 def _merge_blueprint_funcs(self, app: App, name: str) -> None:380 def extend(bp_dict, parent_dict):380 def extend(381 bp_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],382 parent_dict: dict[ft.AppOrBlueprintKey, list[t.Any]],383 ) -> None:384 for key, values in bp_dict.items():385 key = name if key is None else f"{name}.{key}"386 parent_dict[key].extend(values)387
212 unmodified lines
600 the blueprint. Equivalent to :meth:`.Flask.errorhandler`.601 """602603 def decorator(f: T_error_handler) -> T_error_handler:601 self.record_once(lambda s: s.app.errorhandler(code)(f))604 def from_blueprint(state: BlueprintSetupState) -> None:605 state.app.errorhandler(code)(f)606607 self.record_once(from_blueprint)608 return f609610 return decorator611
21 unmodified lines
modified:src/flask/sansio/scaffold.py+35 added-33 removed
6 unmodified lines
7import typing as t8from collections import defaultdict9from functools import update_wrapper1011import click12from jinja2 import FileSystemLoader13from werkzeug.exceptions import default_exceptions14from werkzeug.exceptions import HTTPException15from werkzeug.utils import cached_property
6 unmodified lines
22# a singleton sentinel value for parameter defaults23_sentinel = object()2425F = t.TypeVar("F", bound=t.Callable[..., t.Any])25T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable)26T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable[t.Any])27T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable)28T_error_handler = t.TypeVar("T_error_handler", bound=ft.ErrorHandlerCallable)29T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)30T_template_context_processor = t.TypeVar(
8 unmodified lines
3940def setupmethod(f: F) -> F:41 f_name = f.__name__4242 def wrapper_func(self, *args: t.Any, **kwargs: t.Any) -> t.Any:43 def wrapper_func(self: Scaffold, *args: t.Any, **kwargs: t.Any) -> t.Any:44 self._check_setup_finished(f_name)45 return f(self, *args, **kwargs)4647 return t.cast(F, update_wrapper(wrapper_func, f))
23 unmodified lines
7172 def __init__(73 self,74 import_name: str,74 static_folder: str | os.PathLike | None = None,75 static_folder: str | os.PathLike[str] | None = None,76 static_url_path: str | None = None,76 template_folder: str | os.PathLike | None = None,77 template_folder: str | os.PathLike[str] | None = None,78 root_path: str | None = None,79 ):80 #: The name of the package or module that this object belongs81 #: to. Do not change this once it is set by the constructor.
17 unmodified lines
99 #: The Click command group for registering CLI commands for this100 #: object. The commands are available from the ``flask`` command101 #: once the application has been discovered and blueprints have102 #: been registered.102 self.cli = AppGroup()103 self.cli: click.Group = AppGroup()104105 #: A dictionary mapping endpoint names to view functions.106 #:107 #: To register a view function, use the :meth:`route` decorator.108 #:109 #: This data structure is internal. It should not be modified110 #: directly and its format may change at any time.110 self.view_functions: dict[str, t.Callable] = {}111 self.view_functions: dict[str, ft.RouteCallable] = {}112113 #: A data structure of registered error handlers, in the format114 #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is115 #: the name of a blueprint the handlers are active for, or
36 unmodified lines
152 #:153 #: This data structure is internal. It should not be modified154 #: directly and its format may change at any time.155 self.after_request_funcs: dict[155 ft.AppOrBlueprintKey, list[ft.AfterRequestCallable]156 ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]157 ] = defaultdict(list)158159 #: A data structure of functions to call at the end of each160 #: request even if an exception is raised, in the format
72 unmodified lines
233 else:234 return None235236 @static_folder.setter236 def static_folder(self, value: str | os.PathLike | None) -> None:237 def static_folder(self, value: str | os.PathLike[str] | None) -> None:238 if value is not None:239 value = os.fspath(value).rstrip(r"\/")240241 self._static_folder = value
45 unmodified lines
287 def _method_route(288 self,289 method: str,290 rule: str,290 options: dict,291 options: dict[str, t.Any],292 ) -> t.Callable[[T_route], T_route]:293 if "methods" in options:294 raise TypeError("Use the 'route' decorator to use the 'methods' argument.")295
404 unmodified lines
700 else:701 return exc_class, None702703703def _endpoint_from_view_func(view_func: t.Callable) -> str:704def _endpoint_from_view_func(view_func: ft.RouteCallable) -> str:705 """Internal helper that returns the default endpoint for a given706 function. This always is the function name.707 """708 assert view_func is not None, "expected view func if endpoint is not provided."
8 unmodified lines
717 except ValueError:718 return False719720720def _find_package_path(import_name):721def _find_package_path(import_name: str) -> str:722 """Find the path that contains the package or module."""723 root_mod_name, _, _ = import_name.partition(".")724725 try:
8 unmodified lines
734 # - the module name is __main__735 # - we raised `ValueError` due to `root_spec` being `None`736 return os.getcwd()737738 if root_spec.submodule_search_locations:737 if root_spec.origin in {"namespace", None}:738 # namespace package739 package_spec = importlib.util.find_spec(import_name)739 if root_spec.origin is None or root_spec.origin == "namespace":740 # namespace package741 package_spec = importlib.util.find_spec(import_name)742741 if package_spec is not None and package_spec.submodule_search_locations:742 # Pick the path in the namespace that contains the submodule.743 package_path = pathlib.Path(744 os.path.commonpath(package_spec.submodule_search_locations)745 )746 search_location = next(747 location748 for location in root_spec.submodule_search_locations749 if _path_is_relative_to(package_path, location)750 )751 else:752 # Pick the first path.753 search_location = root_spec.submodule_search_locations[0]743 if package_spec is not None and package_spec.submodule_search_locations:744 # Pick the path in the namespace that contains the submodule.745 package_path = pathlib.Path(746 os.path.commonpath(package_spec.submodule_search_locations)747 )748 search_location = next(749 location750 for location in root_spec.submodule_search_locations751 if _path_is_relative_to(package_path, location)752 )753 else:754 # Pick the first path.755 search_location = root_spec.submodule_search_locations[0]756755 return os.path.dirname(search_location)756 elif root_spec.submodule_search_locations:757 # package with __init__.py758 return os.path.dirname(os.path.dirname(root_spec.origin))757 return os.path.dirname(search_location)758 else:759 # package with __init__.py760 return os.path.dirname(os.path.dirname(root_spec.origin))761 else:762 # module761 return os.path.dirname(root_spec.origin)763 return os.path.dirname(root_spec.origin) # type: ignore[type-var, return-value]764765764def find_package(import_name: str):766def find_package(import_name: str) -> tuple[str | None, str]:767 """Find the prefix that a package is installed under, and the path768 that it would be imported from.769770 The prefix is the directory containing the standard directory
34 unmodified lines
modified:src/flask/app.py+26 added-19 removed
1from __future__ import annotations23import collections.abc as cabc4import os5import sys6import typing as t7import weakref7from collections.abc import Iterator as _abc_Iterator8from datetime import timedelta9from inspect import iscoroutinefunction10from itertools import chain11from types import TracebackType
41 unmodified lines
53from .wrappers import Request54from .wrappers import Response5556if t.TYPE_CHECKING: # pragma: no cover57 from _typeshed.wsgi import StartResponse58 from _typeshed.wsgi import WSGIEnvironment5960 from .testing import FlaskClient61 from .testing import FlaskCliRunner6263T_shell_context_processor = t.TypeVar(
138 unmodified lines
202 )203204 #: The class that is used for request objects. See :class:`~flask.Request`205 #: for more information.203 request_class = Request206 request_class: type[Request] = Request207208 #: The class that is used for response objects. See209 #: :class:`~flask.Response` for more information.207 response_class = Response210 response_class: type[Response] = Response211212 #: the session interface to use. By default an instance of213 #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.214 #:
3 unmodified lines
218 def __init__(219 self,220 import_name: str,221 static_url_path: str | None = None,219 static_folder: str | os.PathLike | None = "static",222 static_folder: str | os.PathLike[str] | None = "static",223 static_host: str | None = None,224 host_matching: bool = False,225 subdomain_matching: bool = False,223 template_folder: str | os.PathLike | None = "templates",226 template_folder: str | os.PathLike[str] | None = "templates",227 instance_path: str | None = None,228 instance_relative_config: bool = False,229 root_path: str | None = None,230 ):
53 unmodified lines
284285 if isinstance(value, timedelta):286 return int(value.total_seconds())287285 return value288 return value # type: ignore[no-any-return]289290 def send_static_file(self, filename: str) -> Response:291 """The view function used to serve files from292 :attr:`static_folder`. A route is automatically registered for
156 unmodified lines
449 or not isinstance(request.routing_exception, RequestRedirect)450 or request.routing_exception.code in {307, 308}451 or request.method in {"GET", "HEAD", "OPTIONS"}452 ):450 raise request.routing_exception # type: ignore453 raise request.routing_exception # type: ignore[misc]454455 from .debughelpers import FormDataRoutingRedirect456457 raise FormDataRoutingRedirect(request)458456 def update_template_context(self, context: dict) -> None:459 def update_template_context(self, context: dict[str, t.Any]) -> None:460 """Update the template context with some commonly used variables.461 This injects request, session, config and g into the template462 context as well as everything template context processors want463 to inject. Note that the as of Flask 0.6, the original values
19 unmodified lines
483 context.update(self.ensure_sync(func)())484485 context.update(orig_ctx)486484 def make_shell_context(self) -> dict:487 def make_shell_context(self) -> dict[str, t.Any]:488 """Returns the shell context for an interactive shell for this489 application. This runs all the registered shell context490 processors.491
234 unmodified lines
726727 handler = self._find_error_handler(e, request.blueprints)728 if handler is None:729 return e727 return self.ensure_sync(handler)(e)730 return self.ensure_sync(handler)(e) # type: ignore[no-any-return]731732 def handle_user_exception(733 self, e: Exception734 ) -> HTTPException | ft.ResponseReturnValue:
23 unmodified lines
758759 if handler is None:760 raise761759 return self.ensure_sync(handler)(e)762 return self.ensure_sync(handler)(e) # type: ignore[no-any-return]763764 def handle_exception(self, e: Exception) -> Response:765 """Handle an exception that did not have an error handler766 associated with it, or that was raised from an error handler.
84 unmodified lines
851 ):852 return self.make_default_options_response()853 # otherwise dispatch to the handler for that endpoint854 view_args: dict[str, t.Any] = req.view_args # type: ignore[assignment]852 return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)855 return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) # type: ignore[no-any-return]856857 def full_dispatch_request(self) -> Response:858 """Dispatches the request and on top of that performs request859 pre and postprocessing as well as HTTP exception catching and
55 unmodified lines
915 rv = self.response_class()916 rv.allow.update(methods)917 return rv918916 def ensure_sync(self, func: t.Callable) -> t.Callable:919 def ensure_sync(self, func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:920 """Ensure that the function is synchronous for WSGI workers.921 Plain ``def`` functions are returned as-is. ``async def``922 functions are wrapped to run and wait for the response.923
6 unmodified lines
930931 return func932933 def async_to_sync(931 self, func: t.Callable[..., t.Coroutine]934 self, func: t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]935 ) -> t.Callable[..., t.Any]:936 """Return a sync function that will run the coroutine function.937938 .. code-block:: python
229 unmodified lines
1168 )11691170 # make sure the body is an instance of the response class1171 if not isinstance(rv, self.response_class):1169 if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, _abc_Iterator):1172 if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, cabc.Iterator):1173 # let the response class set the status and headers instead of1174 # waiting to do it manually, so that the class can handle any1175 # special logic1176 rv = self.response_class(
65 unmodified lines
1242 for before_func in self.before_request_funcs[name]:1243 rv = self.ensure_sync(before_func)()12441245 if rv is not None:1243 return rv1246 return rv # type: ignore[no-any-return]12471248 return None12491250 def process_response(self, response: Response) -> Response:
104 unmodified lines
1355 .. versionadded:: 0.91356 """1357 return AppContext(self)13581356 def request_context(self, environ: dict) -> RequestContext:1359 def request_context(self, environ: WSGIEnvironment) -> RequestContext:1360 """Create a :class:`~flask.ctx.RequestContext` representing a1361 WSGI environment. Use a ``with`` block to push the context,1362 which will make :data:`request` point at this request.1363
63 unmodified lines
1427 return self.request_context(builder.get_environ())1428 finally:1429 builder.close()14301428 def wsgi_app(self, environ: dict, start_response: t.Callable) -> t.Any:1431 def wsgi_app(1432 self, environ: WSGIEnvironment, start_response: StartResponse1433 ) -> cabc.Iterable[bytes]:1434 """The actual WSGI application. This is not implemented in1435 :meth:`__call__` so that middlewares can be applied without1436 losing a reference to the app object. Instead of doing this::1437
39 unmodified lines
1477 error = None14781479 ctx.pop(error)14801476 def __call__(self, environ: dict, start_response: t.Callable) -> t.Any:1481 def __call__(1482 self, environ: WSGIEnvironment, start_response: StartResponse1483 ) -> cabc.Iterable[bytes]:1484 """The WSGI server calls the Flask application object as the1485 WSGI application. This calls :meth:`wsgi_app`, which can be1486 wrapped to apply middleware.1487 """
1 unmodified line
modified:src/flask/blueprints.py+1 added-1 removed
37 unmodified lines
3839 if isinstance(value, timedelta):40 return int(value.total_seconds())4142 return value42 return value # type: ignore[no-any-return]4344 def send_static_file(self, filename: str) -> Response:45 """The view function used to serve files from46 :attr:`static_folder`. A route is automatically registered for
45 unmodified lines
modified:src/flask/cli.py+88 added-49 removed
1from __future__ import annotations23import ast4import collections.abc as cabc5import importlib.metadata6import inspect7import os8import platform
2 unmodified lines
11import traceback12import typing as t13from functools import update_wrapper14from operator import itemgetter15from types import ModuleType1617import click18from click.core import ParameterSource19from werkzeug import run_simple
4 unmodified lines
24from .helpers import get_debug_flag25from .helpers import get_load_dotenv2627if t.TYPE_CHECKING:28 import ssl2930 from _typeshed.wsgi import StartResponse31 from _typeshed.wsgi import WSGIApplication32 from _typeshed.wsgi import WSGIEnvironment3334 from .app import Flask353637class NoAppException(click.UsageError):38 """Raised if an application cannot be found or loaded."""394033def find_best_app(module):41def find_best_app(module: ModuleType) -> Flask:42 """Given a module instance this tries to find the best possible43 application in the module or raises an exception.44 """45 from . import Flask
44 unmodified lines
90 " to specify one."91 )929386def _called_with_wrong_args(f):94def _called_with_wrong_args(f: t.Callable[..., Flask]) -> bool:95 """Check whether calling a function raised a ``TypeError`` because96 the call failed or because something in the factory raised the97 error.98
17 unmodified lines
116 # https://docs.python.org/2/library/sys.html#sys.exc_info117 del tb118119112def find_app_by_string(module, app_name):120def find_app_by_string(module: ModuleType, app_name: str) -> Flask:121 """Check if the given string is a variable name or a function. Call122 a function to get the app instance, or return the variable directly.123 """124 from . import Flask
22 unmodified lines
147148 # Parse the positional and keyword arguments as literals.149 try:150 args = [ast.literal_eval(arg) for arg in expr.args]143 kwargs = {kw.arg: ast.literal_eval(kw.value) for kw in expr.keywords}151 kwargs = {152 kw.arg: ast.literal_eval(kw.value)153 for kw in expr.keywords154 if kw.arg is not None155 }156 except ValueError:157 # literal_eval gives cryptic error messages, show a generic158 # message with the full expression instead.159 raise NoAppException(
36 unmodified lines
196 f" '{module.__name__}:{app_name}'."197 )198199188def prepare_import(path):200def prepare_import(path: str) -> str:201 """Given a filename this will try to calculate the python path, add it202 to the search path and return the actual module name that is expected.203 """204 path = os.path.realpath(path)
20 unmodified lines
225226 return ".".join(module_name[::-1])227228217def locate_app(module_name, app_name, raise_if_not_found=True):229@t.overload230def locate_app(231 module_name: str, app_name: str | None, raise_if_not_found: t.Literal[True] = True232) -> Flask:233 ...234235236@t.overload237def locate_app(238 module_name: str, app_name: str | None, raise_if_not_found: t.Literal[False] = ...239) -> Flask | None:240 ...241242243def locate_app(244 module_name: str, app_name: str | None, raise_if_not_found: bool = True245) -> Flask | None:246 try:247 __import__(module_name)248 except ImportError:249 # Reraise the ImportError if it occurred within the imported module.250 # Determine this by checking whether the trace has a depth > 1.223 if sys.exc_info()[2].tb_next:251 if sys.exc_info()[2].tb_next: # type: ignore[union-attr]252 raise NoAppException(253 f"While importing {module_name!r}, an ImportError was"254 f" raised:\n\n{traceback.format_exc()}"255 ) from None256 elif raise_if_not_found:257 raise NoAppException(f"Could not import {module_name!r}.") from None258 else:231 return259 return None260261 module = sys.modules[module_name]262263 if app_name is None:
1 unmodified line
265 else:266 return find_app_by_string(module, app_name)267268241def get_version(ctx, param, value):269def get_version(ctx: click.Context, param: click.Parameter, value: t.Any) -> None:270 if not value or ctx.resilient_parsing:271 return272273 flask_version = importlib.metadata.version("flask")
52 unmodified lines
326 if self._loaded_app is not None:327 return self._loaded_app328329 if self.create_app is not None:302 app = self.create_app()330 app: Flask | None = self.create_app()331 else:332 if self.app_import_path:333 path, name = (334 re.split(r":(?![\\/])", self.app_import_path, maxsplit=1) + [None]
4 unmodified lines
339 for path in ("wsgi.py", "app.py"):340 import_name = prepare_import(path)341 app = locate_app(import_name, None, raise_if_not_found=False)342315 if app:343 if app is not None:344 break345318 if not app:346 if app is None:347 raise NoAppException(348 "Could not locate a Flask application. Use the"349 " 'flask --app' option, 'FLASK_APP' environment"350 " variable, or a 'wsgi.py' or 'app.py' file in the"
10 unmodified lines
361362363pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True)364365F = t.TypeVar("F", bound=t.Callable[..., t.Any])366367338def with_appcontext(f):368def with_appcontext(f: F) -> F:369 """Wraps a callback so that it's guaranteed to be executed with the370 script's application context.371372 Custom commands (and their options) registered under ``app.cli`` or
6 unmodified lines
379 ``app.cli`` command and parameter callbacks.380 """381382 @click.pass_context353 def decorator(__ctx, *args, **kwargs):383 def decorator(ctx: click.Context, /, *args: t.Any, **kwargs: t.Any) -> t.Any:384 if not current_app:355 app = __ctx.ensure_object(ScriptInfo).load_app()356 __ctx.with_resource(app.app_context())385 app = ctx.ensure_object(ScriptInfo).load_app()386 ctx.with_resource(app.app_context())387358 return __ctx.invoke(f, *args, **kwargs)388 return ctx.invoke(f, *args, **kwargs)389360 return update_wrapper(decorator, f)390 return update_wrapper(decorator, f) # type: ignore[return-value]391392393class AppGroup(click.Group):394 """This works similar to a regular click :class:`~click.Group` but it
2 unmodified lines
397398 Not to be confused with :class:`FlaskGroup`.399 """400371 def command(self, *args, **kwargs):401 def command( # type: ignore[override]402 self, *args: t.Any, **kwargs: t.Any403 ) -> t.Callable[[t.Callable[..., t.Any]], click.Command]:404 """This works exactly like the method of the same name on a regular405 :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`406 unless it's disabled by passing ``with_appcontext=False``.407 """408 wrap_for_ctx = kwargs.pop("with_appcontext", True)409378 def decorator(f):410 def decorator(f: t.Callable[..., t.Any]) -> click.Command:411 if wrap_for_ctx:412 f = with_appcontext(f)381 return click.Group.command(self, *args, **kwargs)(f)413 return super(AppGroup, self).command(*args, **kwargs)(f) # type: ignore[no-any-return]414415 return decorator416385 def group(self, *args, **kwargs):417 def group( # type: ignore[override]418 self, *args: t.Any, **kwargs: t.Any419 ) -> t.Callable[[t.Callable[..., t.Any]], click.Group]:420 """This works exactly like the method of the same name on a regular421 :class:`click.Group` but it defaults the group class to422 :class:`AppGroup`.423 """424 kwargs.setdefault("cls", AppGroup)391 return click.Group.group(self, *args, **kwargs)425 return super().group(*args, **kwargs) # type: ignore[no-any-return]426427428def _set_app(ctx: click.Context, param: click.Option, value: str | None) -> str | None:429 if value is None:
148 unmodified lines
578 self.add_command(routes_command)579580 self._loaded_plugin_commands = False581548 def _load_plugin_commands(self):582 def _load_plugin_commands(self) -> None:583 if self._loaded_plugin_commands:584 return585586 if sys.version_info >= (3, 10):
8 unmodified lines
595 self.add_command(ep.load(), ep.name)596597 self._loaded_plugin_commands = True598565 def get_command(self, ctx, name):599 def get_command(self, ctx: click.Context, name: str) -> click.Command | None:600 self._load_plugin_commands()601 # Look up built-in and plugin commands, which should be602 # available even if the app fails to load.603 rv = super().get_command(ctx, name)
13 unmodified lines
617618 # Push an app context for the loaded app unless it is already619 # active somehow. This makes the context available to parameter620 # and command callbacks without needing @with_appcontext.587 if not current_app or current_app._get_current_object() is not app:621 if not current_app or current_app._get_current_object() is not app: # type: ignore[attr-defined]622 ctx.with_resource(app.app_context())623624 return app.cli.get_command(ctx, name)625592 def list_commands(self, ctx):626 def list_commands(self, ctx: click.Context) -> list[str]:627 self._load_plugin_commands()628 # Start with the built-in and plugin commands.629 rv = set(super().list_commands(ctx))630 info = ctx.ensure_object(ScriptInfo)
47 unmodified lines
678679 return super().parse_args(ctx, args)680681648def _path_is_ancestor(path, other):682def _path_is_ancestor(path: str, other: str) -> bool:683 """Take ``other`` and remove the length of ``path`` from it. Then join it684 to ``path``. If it is the original value, ``path`` is an ancestor of685 ``other``."""686 return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other687688655def load_dotenv(path: str | os.PathLike | None = None) -> bool:689def load_dotenv(path: str | os.PathLike[str] | None = None) -> bool:690 """Load "dotenv" files in order of precedence to set environment variables.691692 If an env var is already set it is not overwritten, so earlier files in the693 list are preferred over later files.
52 unmodified lines
746747 return loaded # True if at least one file was located and loaded.748749716def show_server_banner(debug, app_import_path):750def show_server_banner(debug: bool, app_import_path: str | None) -> None:751 """Show extra startup messages the first time the server is run,752 ignoring the reloader.753 """754 if is_running_from_reloader():
13 unmodified lines
768 """769770 name = "path"771738 def __init__(self):772 def __init__(self) -> None:773 self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)774741 def convert(self, value, param, ctx):775 def convert(776 self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None777 ) -> t.Any:778 try:779 import ssl780 except ImportError:781 raise click.BadParameter(
26 unmodified lines
808809 raise810811776def _validate_key(ctx, param, value):812def _validate_key(ctx: click.Context, param: click.Parameter, value: t.Any) -> t.Any:813 """The ``--key`` option must be specified when ``--cert`` is a file.814 Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.815 """816 cert = ctx.params.get("cert")
36 unmodified lines
853 OS's path separator (``:``, ``;`` on Windows). Each value is854 validated as a :class:`click.Path` type.855 """856821 def convert(self, value, param, ctx):857 def convert(858 self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None859 ) -> t.Any:860 items = self.split_envvar_value(value)823 super_convert = super().convert824 return [super_convert(item, param, ctx) for item in items]861 return [super().convert(item, param, ctx) for item in items]862863864@click.command("run", short_help="Run a development server.")865@click.option("--host", "-h", default="127.0.0.1", help="The interface to bind to.")
48 unmodified lines
914 ),915)916@pass_script_info917def run_command(881 info,882 host,883 port,884 reload,885 debugger,886 with_threads,887 cert,888 extra_files,889 exclude_patterns,890):918 info: ScriptInfo,919 host: str,920 port: int,921 reload: bool,922 debugger: bool,923 with_threads: bool,924 cert: ssl.SSLContext | tuple[str, str | None] | t.Literal["adhoc"] | None,925 extra_files: list[str] | None,926 exclude_patterns: list[str] | None,927) -> None:928 """Run a local development server.929930 This server is for development purposes only. It does not provide931 the stability, security, or performance of production WSGI servers.
1 unmodified line
933 The reloader and debugger are enabled by default with the '--debug'934 option.935 """936 try:900 app = info.load_app()937 app: WSGIApplication = info.load_app()938 except Exception as e:939 if is_running_from_reloader():940 # When reloading, print out the error immediately, but raise941 # it later so the debugger or server can handle it.942 traceback.print_exc()943 err = e944908 def app(environ, start_response):945 def app(946 environ: WSGIEnvironment, start_response: StartResponse947 ) -> cabc.Iterable[bytes]:948 raise err from None949950 else:951 # When not reloading, raise the error immediately so the
42 unmodified lines
994 f"Python {sys.version} on {sys.platform}\n"995 f"App: {current_app.import_name}\n"996 f"Instance: {current_app.instance_path}"997 )959 ctx: dict = {}998 ctx: dict[str, t.Any] = {}9991000 # Support the regular Python interpreter startup script if someone1001 # is using it.1002 startup = os.environ.get("PYTHONSTARTUP")
107 unmodified lines
modified:src/flask/config.py+35 added-10 removed
6 unmodified lines
7import typing as t89from werkzeug.utils import import_string1011if t.TYPE_CHECKING:12 import typing_extensions as te1314 from .sansio.app import App151617T = t.TypeVar("T")181912class ConfigAttribute:20class ConfigAttribute(t.Generic[T]):21 """Makes an attribute forward to the config"""2215 def __init__(self, name: str, get_converter: t.Callable | None = None) -> None:23 def __init__(24 self, name: str, get_converter: t.Callable[[t.Any], T] | None = None25 ) -> None:26 self.__name__ = name27 self.get_converter = get_converter2819 def __get__(self, obj: t.Any, owner: t.Any = None) -> t.Any:29 @t.overload30 def __get__(self, obj: None, owner: None) -> te.Self:31 ...3233 @t.overload34 def __get__(self, obj: App, owner: type[App]) -> T:35 ...3637 def __get__(self, obj: App | None, owner: type[App] | None = None) -> T | te.Self:38 if obj is None:39 return self4041 rv = obj.config[self.__name__]4243 if self.get_converter is not None:44 rv = self.get_converter(rv)25 return rv4546 return rv # type: ignore[no-any-return]4727 def __set__(self, obj: t.Any, value: t.Any) -> None:48 def __set__(self, obj: App, value: t.Any) -> None:49 obj.config[self.__name__] = value505131class Config(dict):52class Config(dict): # type: ignore[type-arg]53 """Works exactly like a dict but provides ways to fill it from files54 or special dictionaries. There are two common patterns to populate the55 config.56
36 unmodified lines
93 :param defaults: an optional dictionary of default values94 """9596 def __init__(76 self, root_path: str | os.PathLike, defaults: dict | None = None97 self,98 root_path: str | os.PathLike[str],99 defaults: dict[str, t.Any] | None = None,100 ) -> None:101 super().__init__(defaults or {})102 self.root_path = root_path103
84 unmodified lines
188 current[tail] = value189190 return True191169 def from_pyfile(self, filename: str | os.PathLike, silent: bool = False) -> bool:192 def from_pyfile(193 self, filename: str | os.PathLike[str], silent: bool = False194 ) -> bool:195 """Updates the values in the config from a Python file. This function196 behaves as if the file was imported as module with the197 :meth:`from_object` function.198
60 unmodified lines
259 self[key] = getattr(obj, key)260261 def from_file(262 self,238 filename: str | os.PathLike,239 load: t.Callable[[t.IO[t.Any]], t.Mapping],263 filename: str | os.PathLike[str],264 load: t.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]],265 silent: bool = False,266 text: bool = True,267 ) -> bool:268 """Update the values in the config from a file that is loaded
104 unmodified lines
modified:src/flask/ctx.py+19 added-10 removed
13 unmodified lines
14from .signals import appcontext_popped15from .signals import appcontext_pushed1617if t.TYPE_CHECKING: # pragma: no cover18 from _typeshed.wsgi import WSGIEnvironment1920 from .app import Flask21 from .sessions import SessionMixin22 from .wrappers import Request23
89 unmodified lines
113 return f"<flask.g of '{ctx.app.name}'>"114 return object.__repr__(self)115116115def after_this_request(f: ft.AfterRequestCallable) -> ft.AfterRequestCallable:117def after_this_request(118 f: ft.AfterRequestCallable[t.Any],119) -> ft.AfterRequestCallable[t.Any]:120 """Executes a function after this request. This is useful to modify121 response objects. The function is passed the response object and has122 to return the same or a new one.123
24 unmodified lines
148 ctx._after_request_functions.append(f)149 return f150151152F = t.TypeVar("F", bound=t.Callable[..., t.Any])153154148def copy_current_request_context(f: t.Callable) -> t.Callable:155def copy_current_request_context(f: F) -> F:156 """A helper function that decorates a function to retain the current157 request context. This is useful when working with greenlets. The moment158 the function is decorated a copy of the request context is created and159 then pushed when the function is called. The current session is also
25 unmodified lines
185 )186187 ctx = ctx.copy()188182 def wrapper(*args, **kwargs):183 with ctx:184 return ctx.app.ensure_sync(f)(*args, **kwargs)189 def wrapper(*args: t.Any, **kwargs: t.Any) -> t.Any:190 with ctx: # type: ignore[union-attr]191 return ctx.app.ensure_sync(f)(*args, **kwargs) # type: ignore[union-attr]192186 return update_wrapper(wrapper, f)193 return update_wrapper(wrapper, f) # type: ignore[return-value]194195196def has_request_context() -> bool:197 """If you have code that wants to test if a request context is there or
47 unmodified lines
245 def __init__(self, app: Flask) -> None:246 self.app = app247 self.url_adapter = app.create_url_adapter(None)248 self.g: _AppCtxGlobals = app.app_ctx_globals_class()242 self._cv_tokens: list[contextvars.Token] = []249 self._cv_tokens: list[contextvars.Token[AppContext]] = []250251 def push(self) -> None:252 """Binds the app context to the current context."""253 self._cv_tokens.append(_cv_app.set(self))
54 unmodified lines
308309 def __init__(310 self,311 app: Flask,305 environ: dict,312 environ: WSGIEnvironment,313 request: Request | None = None,314 session: SessionMixin | None = None,315 ) -> None:316 self.app = app
10 unmodified lines
327 self.session: SessionMixin | None = session328 # Functions that should be executed after the request on the response329 # object. These will be called before the regular "after_request"330 # functions.324 self._after_request_functions: list[ft.AfterRequestCallable] = []331 self._after_request_functions: list[ft.AfterRequestCallable[t.Any]] = []332326 self._cv_tokens: list[tuple[contextvars.Token, AppContext | None]] = []333 self._cv_tokens: list[334 tuple[contextvars.Token[RequestContext], AppContext | None]335 ] = []336337 def copy(self) -> RequestContext:338 """Creates a copy of this request context with the same request object.339 This can be used to move a request context to a different greenlet.
110 unmodified lines
modified:src/flask/debughelpers.py+26 added-8 removed
1from __future__ import annotations23import typing as t45from jinja2.loaders import BaseLoader6from werkzeug.routing import RequestRedirect78from .blueprints import Blueprint9from .globals import request_ctx10from .sansio.app import App1112if t.TYPE_CHECKING:13 from .sansio.scaffold import Scaffold14 from .wrappers import Request151617class UnexpectedUnicodeError(AssertionError, UnicodeError):18 """Raised in places where we want some better error reporting for19 unexpected unicode or binary data.20 """
3 unmodified lines
24 """Raised from request.files during debugging. The idea is that it can25 provide a better error message than just a generic KeyError/BadRequest.26 """2721 def __init__(self, request, key):28 def __init__(self, request: Request, key: str) -> None:29 form_matches = request.form.getlist(key)30 buf = [31 f"You tried to access the file {key!r} in the request.files"32 " dictionary but it does not exist. The mimetype for the"
9 unmodified lines
42 f"This was submitted: {names}"43 )44 self.msg = "".join(buf)4539 def __str__(self):46 def __str__(self) -> str:47 return self.msg484950class FormDataRoutingRedirect(AssertionError):
2 unmodified lines
53 when method is not GET, HEAD or OPTIONS and the status code is not54 307 or 308.55 """5650 def __init__(self, request):57 def __init__(self, request: Request) -> None:58 exc = request.routing_exception59 assert isinstance(exc, RequestRedirect)60 buf = [61 f"A request was sent to '{request.url}', but routing issued"62 f" a redirect to the canonical URL '{exc.new_url}'."63 ]
13 unmodified lines
77 )78 super().__init__("".join(buf))798073def attach_enctype_error_multidict(request):81def attach_enctype_error_multidict(request: Request) -> None:82 """Patch ``request.files.__getitem__`` to raise a descriptive error83 about ``enctype=multipart/form-data``.8485 :param request: The request to patch.86 :meta private:87 """88 oldcls = request.files.__class__8982 class newcls(oldcls):83 def __getitem__(self, key):90 class newcls(oldcls): # type: ignore[valid-type, misc]91 def __getitem__(self, key: str) -> t.Any:92 try:93 return super().__getitem__(key)94 except KeyError as e:95 if key not in request.form:
7 unmodified lines
103 newcls.__module__ = oldcls.__module__104 request.files.__class__ = newcls10510699def _dump_loader_info(loader) -> t.Generator:107def _dump_loader_info(loader: BaseLoader) -> t.Iterator[str]:108 yield f"class: {type(loader).__module__}.{type(loader).__name__}"109 for key, value in sorted(loader.__dict__.items()):110 if key.startswith("_"):111 continue
8 unmodified lines
120 continue121 yield f"{key}: {value!r}"122123116def explain_template_loading_attempts(app: App, template, attempts) -> None:124def explain_template_loading_attempts(125 app: App,126 template: str,127 attempts: list[128 tuple[129 BaseLoader,130 Scaffold,131 tuple[str, str | None, t.Callable[[], bool] | None] | None,132 ]133 ],134) -> None:135 """This should help developers understand what failed"""136 info = [f"Locating template {template!r}:"]137 total_found = 0138 blueprint = None
40 unmodified lines
modified:src/flask/helpers.py+9 added-10 removed
9 unmodified lines
1011import werkzeug.utils12from werkzeug.exceptions import abort as _wz_abort13from werkzeug.utils import redirect as _wz_redirect14from werkzeug.wrappers import Response as BaseResponse1516from .globals import _cv_request17from .globals import current_app18from .globals import request
1 unmodified line
20from .globals import session21from .signals import message_flashed2223if t.TYPE_CHECKING: # pragma: no cover23 from werkzeug.wrappers import Response as BaseResponse2424 from .wrappers import Response252627def get_debug_flag() -> bool:
55 unmodified lines
8384 .. versionadded:: 0.985 """86 try:88 gen = iter(generator_or_function) # type: ignore87 gen = iter(generator_or_function) # type: ignore[arg-type]88 except TypeError:8990 def decorator(*args: t.Any, **kwargs: t.Any) -> t.Any:92 gen = generator_or_function(*args, **kwargs) # type: ignore91 gen = generator_or_function(*args, **kwargs) # type: ignore[operator]92 return stream_with_context(gen)9395 return update_wrapper(decorator, generator_or_function) # type: ignore94 return update_wrapper(decorator, generator_or_function) # type: ignore[arg-type]9597 def generator() -> t.Generator:96 def generator() -> t.Iterator[t.AnyStr | None]:97 ctx = _cv_request.get(None)98 if ctx is None:99 raise RuntimeError(100 "'stream_with_context' can only be used when a request"
19 unmodified lines
120 # pushed. This item is discarded. Then when the iteration continues the121 # real generator is executed.122 wrapped_g = generator()123 next(wrapped_g)125 return wrapped_g124 return wrapped_g # type: ignore[return-value]125126127def make_response(*args: t.Any) -> Response:128 """Sometimes it is necessary to set additional headers in a view. Because
382 unmodified lines
511 )512513514def send_from_directory(516 directory: os.PathLike | str,517 path: os.PathLike | str,515 directory: os.PathLike[str] | str,516 path: os.PathLike[str] | str,517 **kwargs: t.Any,518) -> Response:519 """Send a file from within a directory using :func:`send_file`.520
86 unmodified lines
607 " provided."608 )609610 # filepath is import_name.py for a module, or __init__.py for a package.612 return os.path.dirname(os.path.abspath(filepath))611 return os.path.dirname(os.path.abspath(filepath)) # type: ignore[no-any-return]612613614@lru_cache(maxsize=None)615def _split_blueprint_path(name: str) -> list[str]:
6 unmodified lines
modified:src/flask/logging.py+4 added-1 removed
20 unmodified lines
21 use this for the stream. If you are using file or dict configuration and22 can't import this directly, you can refer to it as23 ``ext://flask.logging.wsgi_errors_stream``.24 """25 if request:25 return request.environ["wsgi.errors"] if request else sys.stderr26 return request.environ["wsgi.errors"] # type: ignore[no-any-return]2728 return sys.stderr293031def has_level_handler(logger: logging.Logger) -> bool:32 """Check if there is a handler in the logging chain that will handle the33 given logger's :meth:`effective level <~logging.Logger.getEffectiveLevel>`.34 """
45 unmodified lines
modified:src/flask/sessions.py+14 added-11 removed
11 unmodified lines
1213from .json.tag import TaggedJSONSerializer1415if t.TYPE_CHECKING: # pragma: no cover16 import typing_extensions as te1718 from .app import Flask19 from .wrappers import Request20 from .wrappers import Response212223# TODO generic when Python > 3.821class SessionMixin(MutableMapping):24class SessionMixin(MutableMapping): # type: ignore[type-arg]25 """Expands a basic dictionary with session attributes."""2627 @property28 def permanent(self) -> bool:
19 unmodified lines
48 #: coded to ``True``.49 accessed = True505152# TODO generic when Python > 3.849class SecureCookieSession(CallbackDict, SessionMixin):53class SecureCookieSession(CallbackDict, SessionMixin): # type: ignore[type-arg]54 """Base class for sessions based on signed cookies.5556 This session backend will set the :attr:`modified` and57 :attr:`accessed` attributes. It cannot reliably track whether a
14 unmodified lines
72 #: different users.73 accessed = False7475 def __init__(self, initial: t.Any = None) -> None:72 def on_update(self) -> None:76 def on_update(self: te.Self) -> None:77 self.modified = True78 self.accessed = True7980 super().__init__(initial, on_update)
100 unmodified lines
181 return isinstance(obj, self.null_session_class)182183 def get_cookie_name(self, app: Flask) -> str:184 """The name of the session cookie. Uses``app.config["SESSION_COOKIE_NAME"]``."""181 return app.config["SESSION_COOKIE_NAME"]185 return app.config["SESSION_COOKIE_NAME"] # type: ignore[no-any-return]186187 def get_cookie_domain(self, app: Flask) -> str | None:188 """The value of the ``Domain`` parameter on the session cookie. If not set,189 browsers will only send the cookie to the exact domain it was set from.
3 unmodified lines
193194 .. versionchanged:: 2.3195 Not set by default, does not fall back to ``SERVER_NAME``.196 """193 rv = app.config["SESSION_COOKIE_DOMAIN"]194 return rv if rv else None197 return app.config["SESSION_COOKIE_DOMAIN"] # type: ignore[no-any-return]198199 def get_cookie_path(self, app: Flask) -> str:200 """Returns the path for which the cookie should be valid. The201 default implementation uses the value from the ``SESSION_COOKIE_PATH``202 config var if it's set, and falls back to ``APPLICATION_ROOT`` or203 uses ``/`` if it's ``None``.204 """202 return app.config["SESSION_COOKIE_PATH"] or app.config["APPLICATION_ROOT"]205 return app.config["SESSION_COOKIE_PATH"] or app.config["APPLICATION_ROOT"] # type: ignore[no-any-return]206207 def get_cookie_httponly(self, app: Flask) -> bool:208 """Returns True if the session cookie should be httponly. This209 currently just returns the value of the ``SESSION_COOKIE_HTTPONLY``210 config var.211 """209 return app.config["SESSION_COOKIE_HTTPONLY"]212 return app.config["SESSION_COOKIE_HTTPONLY"] # type: ignore[no-any-return]213214 def get_cookie_secure(self, app: Flask) -> bool:215 """Returns True if the cookie should be secure. This currently216 just returns the value of the ``SESSION_COOKIE_SECURE`` setting.217 """215 return app.config["SESSION_COOKIE_SECURE"]218 return app.config["SESSION_COOKIE_SECURE"] # type: ignore[no-any-return]219217 def get_cookie_samesite(self, app: Flask) -> str:220 def get_cookie_samesite(self, app: Flask) -> str | None:221 """Return ``'Strict'`` or ``'Lax'`` if the cookie should use the222 ``SameSite`` attribute. This currently just returns the value of223 the :data:`SESSION_COOKIE_SAMESITE` setting.224 """222 return app.config["SESSION_COOKIE_SAMESITE"]225 return app.config["SESSION_COOKIE_SAMESITE"] # type: ignore[no-any-return]226227 def get_expiration_time(self, app: Flask, session: SessionMixin) -> datetime | None:228 """A helper method that returns an expiration date for the session229 or ``None`` if the session is linked to the browser session. The
142 unmodified lines
modified:src/flask/templating.py+8 added-10 removed
55 unmodified lines
5657 def __init__(self, app: App) -> None:58 self.app = app5960 def get_source( # type: ignore61 self, environment: Environment, template: str62 ) -> tuple[str, str | None, t.Callable | None]:60 def get_source(61 self, environment: BaseEnvironment, template: str62 ) -> tuple[str, str | None, t.Callable[[], bool] | None]:63 if self.app.config["EXPLAIN_TEMPLATE_LOADING"]:64 return self._get_source_explained(environment, template)65 return self._get_source_fast(environment, template)6667 def _get_source_explained(68 self, environment: Environment, template: str69 ) -> tuple[str, str | None, t.Callable | None]:68 self, environment: BaseEnvironment, template: str69 ) -> tuple[str, str | None, t.Callable[[], bool] | None]:70 attempts = []71 rv: tuple[str, str | None, t.Callable[[], bool] | None] | None72 trv: None | (tuple[str, str | None, t.Callable[[], bool] | None]) = None73
14 unmodified lines
88 return trv89 raise TemplateNotFound(template)9091 def _get_source_fast(92 self, environment: Environment, template: str93 ) -> tuple[str, str | None, t.Callable | None]:92 self, environment: BaseEnvironment, template: str93 ) -> tuple[str, str | None, t.Callable[[], bool] | None]:94 for _srcobj, loader in self._iter_loaders(template):95 try:96 return loader.get_source(environment, template)97 except TemplateNotFound:98 continue99 raise TemplateNotFound(template)100101 def _iter_loaders(102 self, template: str103 ) -> t.Generator[tuple[Scaffold, BaseLoader], None, None]:101 def _iter_loaders(self, template: str) -> t.Iterator[tuple[Scaffold, BaseLoader]]:102 loader = self.app.jinja_loader103 if loader is not None:104 yield self.app, loader105
114 unmodified lines
modified:src/flask/testing.py+8 added-5 removed
15 unmodified lines
16from .cli import ScriptInfo17from .sessions import SessionMixin1819if t.TYPE_CHECKING: # pragma: no cover20 from _typeshed.wsgi import WSGIEnvironment21 from werkzeug.test import TestResponse2223 from .app import Flask24
109 unmodified lines
134135 @contextmanager136 def session_transaction(137 self, *args: t.Any, **kwargs: t.Any137 ) -> t.Generator[SessionMixin, None, None]:138 ) -> t.Iterator[SessionMixin]:139 """When used in combination with a ``with`` statement this opens a140 session transaction. This can be used to modify the session that141 the test client uses. Once the ``with`` block is left the session is142 stored back.
38 unmodified lines
181 ctx.request.path,182 resp.headers.getlist("Set-Cookie"),183 )184184 def _copy_environ(self, other):185 def _copy_environ(self, other: WSGIEnvironment) -> WSGIEnvironment:186 out = {**self.environ_base, **other}187188 if self.preserve_context:189 out["werkzeug.debug.preserve_context"] = self._new_contexts.append190191 return out192192 def _request_from_builder_args(self, args, kwargs):193 def _request_from_builder_args(194 self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any]195 ) -> BaseRequest:196 kwargs["environ_base"] = self._copy_environ(kwargs.get("environ_base", {}))197 builder = EnvironBuilder(self.application, *args, **kwargs)198199 try:
12 unmodified lines
212 args[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest)213 ):214 if isinstance(args[0], werkzeug.test.EnvironBuilder):215 builder = copy(args[0])213 builder.environ_base = self._copy_environ(builder.environ_base or {})216 builder.environ_base = self._copy_environ(builder.environ_base or {}) # type: ignore[arg-type]217 request = builder.get_request()218 elif isinstance(args[0], dict):219 request = EnvironBuilder.from_environ(220 args[0], app=self.application, environ_base=self._copy_environ({})
68 unmodified lines
289290 :return: a :class:`~click.testing.Result` object.291 """292 if cli is None:290 cli = self.app.cli # type: ignore293 cli = self.app.cli294295 if "obj" not in kwargs:296 kwargs["obj"] = ScriptInfo(create_app=lambda: self.app)297
1 unmodified line
modified:src/flask/typing.py+4 added-2 removed
66 unmodified lines
67]68TemplateFilterCallable = t.Callable[..., t.Any]69TemplateGlobalCallable = t.Callable[..., t.Any]70TemplateTestCallable = t.Callable[..., bool]71URLDefaultCallable = t.Callable[[str, dict], None]72URLValuePreprocessorCallable = t.Callable[[t.Optional[str], t.Optional[dict]], None]71URLDefaultCallable = t.Callable[[str, t.Dict[str, t.Any]], None]72URLValuePreprocessorCallable = t.Callable[73 [t.Optional[str], t.Optional[t.Dict[str, t.Any]]], None74]7576# This should take Exception, but that either breaks typing the argument77# with a specific exception, or decorating multiple times with different78# exceptions (and using a union type on the argument).
12 unmodified lines
modified:src/flask/views.py+6 added-4 removed
4 unmodified lines
5from . import typing as ft6from .globals import current_app7from .globals import request89F = t.TypeVar("F", bound=t.Callable[..., t.Any])1011http_method_funcs = frozenset(12 ["get", "post", "head", "options", "delete", "put", "trace", "patch"]13)14
45 unmodified lines
60 #: to top, so the first decorator in the list would be the bottom61 #: decorator.62 #:63 #: .. versionadded:: 0.862 decorators: t.ClassVar[list[t.Callable]] = []64 decorators: t.ClassVar[list[t.Callable[[F], F]]] = []6566 #: Create a new instance of this view class for every request by67 #: default. If a view subclass sets this to ``False``, the same68 #: instance is used for every request.
37 unmodified lines
106 def view(**kwargs: t.Any) -> ft.ResponseReturnValue:107 self = view.view_class( # type: ignore[attr-defined]108 *class_args, **class_kwargs109 )108 return current_app.ensure_sync(self.dispatch_request)(**kwargs)110 return current_app.ensure_sync(self.dispatch_request)(**kwargs) # type: ignore[no-any-return]111112 else:113 self = cls(*class_args, **class_kwargs)114115 def view(**kwargs: t.Any) -> ft.ResponseReturnValue:114 return current_app.ensure_sync(self.dispatch_request)(**kwargs)116 return current_app.ensure_sync(self.dispatch_request)(**kwargs) # type: ignore[no-any-return]117118 if cls.decorators:119 view.__name__ = name120 view.__module__ = cls.__module__
66 unmodified lines
187 if meth is None and request.method == "HEAD":188 meth = getattr(self, "get", None)189190 assert meth is not None, f"Unimplemented method {request.method!r}"189 return current_app.ensure_sync(meth)(**kwargs)191 return current_app.ensure_sync(meth)(**kwargs) # type: ignore[no-any-return]
modified:src/flask/wrappers.py+5 added-4 removed
1 unmodified line
23import typing as t45from werkzeug.exceptions import BadRequest6from werkzeug.exceptions import HTTPException7from werkzeug.wrappers import Request as RequestBase8from werkzeug.wrappers import Response as ResponseBase910from . import json
38 unmodified lines
49 #: If matching the URL failed, this is the exception that will be50 #: raised / was raised as part of the request handling. This is51 #: usually a :exc:`~werkzeug.exceptions.NotFound` exception or52 #: something similar.52 routing_exception: Exception | None = None53 routing_exception: HTTPException | None = None5455 @property55 def max_content_length(self) -> int | None: # type: ignore56 def max_content_length(self) -> int | None: # type: ignore[override]57 """Read-only view of the ``MAX_CONTENT_LENGTH`` config key."""58 if current_app:58 return current_app.config["MAX_CONTENT_LENGTH"]59 return current_app.config["MAX_CONTENT_LENGTH"] # type: ignore[no-any-return]60 else:61 return None6263 @property
103 unmodified lines
167 See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in168 Werkzeug's docs.169 """170 if current_app:170 return current_app.config["MAX_COOKIE_SIZE"]171 return current_app.config["MAX_COOKIE_SIZE"] # type: ignore[no-any-return]172173 # return Werkzeug's default when not in an app context174 return super().max_cookie_size
modified:.pre-commit-config.yaml+1 added-1 removed
1ci:2 autoupdate_schedule: monthly3repos:4 - repo: https://github.com/astral-sh/ruff-pre-commit5 rev: v0.1.95 rev: v0.1.136 hooks:7 - id: ruff8 - id: ruff-format9 - repo: https://github.com/pre-commit/pre-commit-hooks
7 unmodified lines
modified:CHANGES.rst+5 added-1 removed
1Version 3.0.12-------------34Unreleased4Released 2024-01-1856- Correct type for ``path`` argument to ``send_file``. :issue:`5230`7- Fix a typo in an error message for the ``flask run --key`` option. :pr:`5344`8- Session data is untagged without relying on the built-in ``json.loads``9 ``object_hook``. This allows other JSON providers that don't implement that.10 :issue:`5381`11- Address more type findings when using mypy strict mode. :pr:`5383`121314Version 3.0.015-------------
1528 unmodified lines
modified:pyproject.toml+2 added-16 removed
1[project]2name = "Flask"3version = "3.0.1.dev"3version = "3.0.1"4description = "A simple framework for building complex web applications."5readme = "README.rst"6license = {file = "LICENSE.rst"}7maintainers = [{name = "Pallets", email = "contact@palletsprojects.com"}]
73 unmodified lines
81python_version = "3.8"82files = ["src/flask", "tests/typing"]83show_error_codes = true84pretty = true85#strict = true86allow_redefinition = true87disallow_subclassing_any = true88#disallow_untyped_calls = true89#disallow_untyped_defs = true90#disallow_incomplete_defs = true91no_implicit_optional = true92local_partial_types = true93#no_implicit_reexport = true94strict_equality = true95warn_redundant_casts = true96warn_unused_configs = true97warn_unused_ignores = true98#warn_return_any = true99#warn_unreachable = true85strict = true8687[[tool.mypy.overrides]]88module = [89 "asgiref.*",
26 unmodified lines