Merge pull request #3973 from pgjones/typing
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by GitHub · parents b8ddd52, 7723709 · Browse files · 27 files·+869 added−461 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
27 files+869 added−461 removed
- other:+869 added−461 removed
Provenance
- Commit
1a8549d- Tree
99f8ce3- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
b8ddd52- Parent 2
7723709
27 files changed+869 added−461 removed
modified:.github/workflows/tests.yaml+1 added
29 unmodified lines30313233343536373816 unmodified lines29 unmodified lines - {name: '3.8', python: '3.8', os: ubuntu-latest, tox: py38} - {name: '3.7', python: '3.7', os: ubuntu-latest, tox: py37} - {name: '3.6', python: '3.6', os: ubuntu-latest, tox: py36} - {name: 'PyPy', python: pypy3, os: ubuntu-latest, tox: pypy3} - {name: Typing, python: '3.9', os: ubuntu-latest, tox: typing} steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 with:16 unmodified linesadded:requirements/typing.in+1 added
1+mypyadded:requirements/typing.txt+14 added
1+#2+# This file is autogenerated by pip-compile3+# To update, run:4+#5+# pip-compile requirements/typing.in6+#7+mypy-extensions==0.4.38+ # via mypy9+mypy==0.81210+ # via -r requirements/typing.in11+typed-ast==1.4.312+ # via mypy13+typing-extensions==3.7.4.314+ # via mypymodified:src/flask/json/__init__.py+37 added-20 removed
1 import io2 import json as _json3+import typing as t4 import uuid5 import warnings6 from datetime import date7 7-from jinja2.utils import htmlsafe_json_dumps as _jinja_htmlsafe_dumps8+from jinja2.utils import htmlsafe_json_dumps as _jinja_htmlsafe_dumps # type: ignore9 from werkzeug.http import http_date10 11 from ..globals import current_app12 from ..globals import request13 14+if t.TYPE_CHECKING:15+ from ..app import Flask16+ from ..wrappers import Response17+18 try:19 import dataclasses20 except ImportError:21 # Python < 3.717- dataclasses = None22+ dataclasses = None # type: ignore23 24 25 class JSONEncoder(_json.JSONEncoder):26 """The default JSON encoder. Handles extra types compared to the11 unmodified lines38 Assign a subclass of this to :attr:`flask.Flask.json_encoder` or39 :attr:`flask.Blueprint.json_encoder` to override the default.40 """41 37- def default(self, o):42+ def default(self, o: t.Any) -> t.Any:43 """Convert ``o`` to a JSON serializable type. See44 :meth:`json.JSONEncoder.default`. Python does not support45 overriding how basic types like ``str`` or ``list`` are46 serialized, they are handled before this method.5 unmodified lines52 if dataclasses and dataclasses.is_dataclass(o):53 return dataclasses.asdict(o)54 if hasattr(o, "__html__"):55 return str(o.__html__())51- return super().default(self, o)56+ return super().default(o)57 58 59 class JSONDecoder(_json.JSONDecoder):60 """The default JSON decoder.5 unmodified lines66 :attr:`flask.Blueprint.json_decoder` to override the default.67 """68 69 65-def _dump_arg_defaults(kwargs, app=None):70+def _dump_arg_defaults(71+ kwargs: t.Dict[str, t.Any], app: t.Optional["Flask"] = None72+) -> None:73 """Inject default arguments for dump functions."""74 if app is None:75 app = current_app76 77 if app:71- bp = app.blueprints.get(request.blueprint) if request else None72- cls = bp.json_encoder if bp and bp.json_encoder else app.json_encoder78+ cls = app.json_encoder79+ bp = app.blueprints.get(request.blueprint) if request else None # type: ignore80+ if bp is not None and bp.json_encoder is not None:81+ cls = bp.json_encoder82+83 kwargs.setdefault("cls", cls)84 kwargs.setdefault("ensure_ascii", app.config["JSON_AS_ASCII"])85 kwargs.setdefault("sort_keys", app.config["JSON_SORT_KEYS"])86 else:87 kwargs.setdefault("sort_keys", True)88 kwargs.setdefault("cls", JSONEncoder)89 90 81-def _load_arg_defaults(kwargs, app=None):91+def _load_arg_defaults(92+ kwargs: t.Dict[str, t.Any], app: t.Optional["Flask"] = None93+) -> None:94 """Inject default arguments for load functions."""95 if app is None:96 app = current_app97 98 if app:87- bp = app.blueprints.get(request.blueprint) if request else None88- cls = bp.json_decoder if bp and bp.json_decoder else app.json_decoder99+ cls = app.json_decoder100+ bp = app.blueprints.get(request.blueprint) if request else None # type: ignore101+ if bp is not None and bp.json_decoder is not None:102+ cls = bp.json_decoder103+104 kwargs.setdefault("cls", cls)105 else:106 kwargs.setdefault("cls", JSONDecoder)107 108 94-def dumps(obj, app=None, **kwargs):109+def dumps(obj: t.Any, app: t.Optional["Flask"] = None, **kwargs: t.Any) -> str:110 """Serialize an object to a string of JSON.111 112 Takes the same arguments as the built-in :func:`json.dumps`, with113 some defaults from application configuration.21 unmodified lines135 stacklevel=2,136 )137 138 if isinstance(rv, str):124- return rv.encode(encoding)139+ return rv.encode(encoding) # type: ignore140 141 return rv142 143 129-def dump(obj, fp, app=None, **kwargs):144+def dump(145+ obj: t.Any, fp: t.IO[str], app: t.Optional["Flask"] = None, **kwargs: t.Any146+) -> None:147 """Serialize an object to JSON written to a file object.148 149 Takes the same arguments as the built-in :func:`json.dump`, with150 some defaults from application configuration.15 unmodified lines166 try:167 fp.write("")168 except TypeError:169 show_warning = True153- fp = io.TextIOWrapper(fp, encoding or "utf-8")170+ fp = io.TextIOWrapper(fp, encoding or "utf-8") # type: ignore171 172 if show_warning:173 warnings.warn(174 "Writing to a binary file, and the 'encoding' argument, is"4 unmodified lines179 180 _json.dump(obj, fp, **kwargs)181 182 166-def loads(s, app=None, **kwargs):183+def loads(s: str, app: t.Optional["Flask"] = None, **kwargs: t.Any) -> t.Any:184 """Deserialize an object from a string of JSON.185 186 Takes the same arguments as the built-in :func:`json.loads`, with187 some defaults from application configuration.27 unmodified lines215 216 return _json.loads(s, **kwargs)217 218 202-def load(fp, app=None, **kwargs):219+def load(fp: t.IO[str], app: t.Optional["Flask"] = None, **kwargs: t.Any) -> t.Any:220 """Deserialize an object from JSON read from a file object.221 222 Takes the same arguments as the built-in :func:`json.load`, with223 some defaults from application configuration.19 unmodified lines243 stacklevel=2,244 )245 246 if isinstance(fp.read(0), bytes):230- fp = io.TextIOWrapper(fp, encoding)247+ fp = io.TextIOWrapper(fp, encoding) # type: ignore248 249 return _json.load(fp, **kwargs)250 251 235-def htmlsafe_dumps(obj, **kwargs):252+def htmlsafe_dumps(obj: t.Any, **kwargs: t.Any) -> str:253 """Serialize an object to a string of JSON with :func:`dumps`, then254 replace HTML-unsafe characters with Unicode escapes and mark the255 result safe with :class:`~markupsafe.Markup`.256 15 unmodified lines272 """273 return _jinja_htmlsafe_dumps(obj, dumps=dumps, **kwargs)274 275 259-def htmlsafe_dump(obj, fp, **kwargs):276+def htmlsafe_dump(obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:277 """Serialize an object to JSON written to a file object, replacing278 HTML-unsafe characters with Unicode escapes. See279 :func:`htmlsafe_dumps` and :func:`dumps`.280 """281 fp.write(htmlsafe_dumps(obj, **kwargs))282 283 267-def jsonify(*args, **kwargs):284+def jsonify(*args: t.Any, **kwargs: t.Any) -> "Response":285 """Serialize data to JSON and wrap it in a :class:`~flask.Response`286 with the :mimetype:`application/json` mimetype.287 288 Uses :func:`dumps` to serialize the data, but ``args`` and62 unmodified linesmodified:src/flask/json/tag.py+42 added-36 removed
38 unmodified lines39 return OrderedDict(value)40 41 app.session_interface.serializer.register(TagOrderedDict, index=0)42 """43+import typing as t44 from base64 import b64decode45 from base64 import b64encode46 from datetime import datetime47 from uuid import UUID12 unmodified lines60 __slots__ = ("serializer",)61 62 #: The tag to mark the serialized object with. If ``None``, this tag is63 #: only used as an intermediate step during tagging.63- key = None64+ key: t.Optional[str] = None65 65- def __init__(self, serializer):66+ def __init__(self, serializer: "TaggedJSONSerializer") -> None:67 """Create a tagger for the given serializer."""68 self.serializer = serializer69 69- def check(self, value):70+ def check(self, value: t.Any) -> bool:71 """Check if the given value should be tagged by this tag."""72 raise NotImplementedError73 73- def to_json(self, value):74+ def to_json(self, value: t.Any) -> t.Any:75 """Convert the Python object to an object that is a valid JSON type.76 The tag will be added later."""77 raise NotImplementedError78 78- def to_python(self, value):79+ def to_python(self, value: t.Any) -> t.Any:80 """Convert the JSON representation back to the correct type. The tag81 will already be removed."""82 raise NotImplementedError83 83- def tag(self, value):84+ def tag(self, value: t.Any) -> t.Any:85 """Convert the value to a valid JSON type and add the tag structure86 around it."""87 return {self.key: self.to_json(value)}88 7 unmodified lines96 97 __slots__ = ()98 key = " di"99 99- def check(self, value):100+ def check(self, value: t.Any) -> bool:101 return (102 isinstance(value, dict)103 and len(value) == 1104 and next(iter(value)) in self.serializer.tags105 )106 106- def to_json(self, value):107+ def to_json(self, value: t.Any) -> t.Any:108 key = next(iter(value))109 return {f"{key}__": self.serializer.tag(value[key])}110 110- def to_python(self, value):111+ def to_python(self, value: t.Any) -> t.Any:112 key = next(iter(value))113 return {key[:-2]: value[key]}114 115 116 class PassDict(JSONTag):117 __slots__ = ()118 118- def check(self, value):119+ def check(self, value: t.Any) -> bool:120 return isinstance(value, dict)121 121- def to_json(self, value):122+ def to_json(self, value: t.Any) -> t.Any:123 # JSON objects may only have string keys, so don't bother tagging the124 # key here.125 return {k: self.serializer.tag(v) for k, v in value.items()}126 3 unmodified lines130 class TagTuple(JSONTag):131 __slots__ = ()132 key = " t"133 133- def check(self, value):134+ def check(self, value: t.Any) -> bool:135 return isinstance(value, tuple)136 136- def to_json(self, value):137+ def to_json(self, value: t.Any) -> t.Any:138 return [self.serializer.tag(item) for item in value]139 139- def to_python(self, value):140+ def to_python(self, value: t.Any) -> t.Any:141 return tuple(value)142 143 144 class PassList(JSONTag):145 __slots__ = ()146 146- def check(self, value):147+ def check(self, value: t.Any) -> bool:148 return isinstance(value, list)149 149- def to_json(self, value):150+ def to_json(self, value: t.Any) -> t.Any:151 return [self.serializer.tag(item) for item in value]152 153 tag = to_json154 1 unmodified line156 class TagBytes(JSONTag):157 __slots__ = ()158 key = " b"159 159- def check(self, value):160+ def check(self, value: t.Any) -> bool:161 return isinstance(value, bytes)162 162- def to_json(self, value):163+ def to_json(self, value: t.Any) -> t.Any:164 return b64encode(value).decode("ascii")165 165- def to_python(self, value):166+ def to_python(self, value: t.Any) -> t.Any:167 return b64decode(value)168 169 170 class TagMarkup(JSONTag):3 unmodified lines174 175 __slots__ = ()176 key = " m"177 177- def check(self, value):178+ def check(self, value: t.Any) -> bool:179 return callable(getattr(value, "__html__", None))180 180- def to_json(self, value):181+ def to_json(self, value: t.Any) -> t.Any:182 return str(value.__html__())183 183- def to_python(self, value):184+ def to_python(self, value: t.Any) -> t.Any:185 return Markup(value)186 187 188 class TagUUID(JSONTag):189 __slots__ = ()190 key = " u"191 191- def check(self, value):192+ def check(self, value: t.Any) -> bool:193 return isinstance(value, UUID)194 194- def to_json(self, value):195+ def to_json(self, value: t.Any) -> t.Any:196 return value.hex197 197- def to_python(self, value):198+ def to_python(self, value: t.Any) -> t.Any:199 return UUID(value)200 201 202 class TagDateTime(JSONTag):203 __slots__ = ()204 key = " d"205 205- def check(self, value):206+ def check(self, value: t.Any) -> bool:207 return isinstance(value, datetime)208 208- def to_json(self, value):209+ def to_json(self, value: t.Any) -> t.Any:210 return http_date(value)211 211- def to_python(self, value):212+ def to_python(self, value: t.Any) -> t.Any:213 return parse_date(value)214 215 216 class TaggedJSONSerializer:25 unmodified lines242 TagUUID,243 TagDateTime,244 ]245 245- def __init__(self):246- self.tags = {}247- self.order = []246+ def __init__(self) -> None:247+ self.tags: t.Dict[str, JSONTag] = {}248+ self.order: t.List[JSONTag] = []249 250 for cls in self.default_tags:251 self.register(cls)252 252- def register(self, tag_class, force=False, index=None):253+ def register(254+ self,255+ tag_class: t.Type[JSONTag],256+ force: bool = False,257+ index: t.Optional[int] = None,258+ ) -> None:259 """Register a new tag with this serializer.260 261 :param tag_class: tag class to register. Will be instantiated with this262 serializer instance.19 unmodified lines282 self.order.append(tag)283 else:284 self.order.insert(index, tag)285 280- def tag(self, value):286+ def tag(self, value: t.Any) -> t.Dict[str, t.Any]:287 """Convert a value to a tagged representation if necessary."""288 for tag in self.order:289 if tag.check(value):290 return tag.tag(value)291 292 return value293 288- def untag(self, value):294+ def untag(self, value: t.Dict[str, t.Any]) -> t.Any:295 """Convert a tagged representation back to the original type."""296 if len(value) != 1:297 return value298 3 unmodified lines302 return value303 304 return self.tags[key].to_python(value[key])305 300- def dumps(self, value):306+ def dumps(self, value: t.Any) -> str:307 """Tag the value and dump it to a compact JSON string."""308 return dumps(self.tag(value), separators=(",", ":"))309 304- def loads(self, value):310+ def loads(self, value: str) -> t.Any:311 """Load data from a JSON string and deserialized any tagged objects."""312 return loads(value, object_hook=self.untag)modified:src/flask/app.py+181 added-111 removed
1 import functools2 import inspect3+import logging4 import os5 import sys6+import typing as t7 import weakref8 from datetime import timedelta9 from itertools import chain10 from threading import Lock11+from types import TracebackType12 13 from werkzeug.datastructures import Headers14 from werkzeug.datastructures import ImmutableDict15 from werkzeug.exceptions import BadRequest1 unmodified line17 from werkzeug.exceptions import HTTPException18 from werkzeug.exceptions import InternalServerError19 from werkzeug.routing import BuildError20 from werkzeug.routing import Map21+from werkzeug.routing import MapAdapter22 from werkzeug.routing import RequestRedirect23 from werkzeug.routing import RoutingException24 from werkzeug.routing import Rule25 from werkzeug.wrappers import Response as BaseResponse30 unmodified lines56 from .signals import request_started57 from .signals import request_tearing_down58 from .templating import DispatchingJinjaLoader59 from .templating import Environment60+from .typing import AfterRequestCallable61+from .typing import BeforeRequestCallable62+from .typing import ErrorHandlerCallable63+from .typing import ResponseReturnValue64+from .typing import TeardownCallable65+from .typing import TemplateContextProcessorCallable66+from .typing import TemplateFilterCallable67+from .typing import TemplateGlobalCallable68+from .typing import TemplateTestCallable69+from .typing import URLDefaultCallable70+from .typing import URLValuePreprocessorCallable71 from .wrappers import Request72 from .wrappers import Response73 74+if t.TYPE_CHECKING:75+ from .blueprints import Blueprint76+ from .testing import FlaskClient77+ from .testing import FlaskCliRunner78 79 if sys.version_info >= (3, 8):80 iscoroutinefunction = inspect.iscoroutinefunction81 else:82 64- def iscoroutinefunction(func):83+ def iscoroutinefunction(func: t.Any) -> bool:84 while inspect.ismethod(func):85 func = func.__func__86 87 while isinstance(func, functools.partial):1 unmodified line89 90 return inspect.iscoroutinefunction(func)91 92 74-def _make_timedelta(value):93+def _make_timedelta(value: t.Optional[timedelta]) -> t.Optional[timedelta]:94 if value is None or isinstance(value, timedelta):95 return value96 97 return timedelta(seconds=value)215 unmodified lines313 #: .. versionchanged:: 1.1.0314 #: This is a ``dict`` instead of an ``ImmutableDict`` to allow315 #: easier configuration.316 #:298- jinja_options = {}317+ jinja_options: dict = {}318 319 #: Default configuration parameters.320 default_config = ImmutableDict(321 {43 unmodified lines365 366 #: the test client that is used with when `test_client` is used.367 #:368 #: .. versionadded:: 0.7350- test_client_class = None369+ test_client_class: t.Optional[t.Type["FlaskClient"]] = None370 371 #: The :class:`~click.testing.CliRunner` subclass, by default372 #: :class:`~flask.testing.FlaskCliRunner` that is used by373 #: :meth:`test_cli_runner`. Its ``__init__`` method should take a374 #: Flask app object as the first argument.375 #:376 #: .. versionadded:: 1.0358- test_cli_runner_class = None377+ test_cli_runner_class: t.Optional[t.Type["FlaskCliRunner"]] = None378 379 #: the session interface to use. By default an instance of380 #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.381 #:1 unmodified line383 session_interface = SecureCookieSessionInterface()384 385 def __init__(386 self,368- import_name,369- static_url_path=None,370- static_folder="static",371- static_host=None,372- host_matching=False,373- subdomain_matching=False,374- template_folder="templates",375- instance_path=None,376- instance_relative_config=False,377- root_path=None,387+ import_name: str,388+ static_url_path: t.Optional[str] = None,389+ static_folder: t.Optional[str] = "static",390+ static_host: t.Optional[str] = None,391+ host_matching: bool = False,392+ subdomain_matching: bool = False,393+ template_folder: t.Optional[str] = "templates",394+ instance_path: t.Optional[str] = None,395+ instance_relative_config: bool = False,396+ root_path: t.Optional[str] = None,397 ):398 super().__init__(399 import_name=import_name,400 static_folder=static_folder,26 unmodified lines427 #: returns ``None`` or raises a :exc:`BuildError` the next function is428 #: tried.429 #:430 #: .. versionadded:: 0.9412- self.url_build_error_handlers = []431+ self.url_build_error_handlers: t.List[432+ t.Callable[[Exception, str, dict], str]433+ ] = []434 435 #: A list of functions that will be called at the beginning of the436 #: first request to this instance. To register a function, use the437 #: :meth:`before_first_request` decorator.438 #:439 #: .. versionadded:: 0.8419- self.before_first_request_funcs = []440+ self.before_first_request_funcs: t.List[BeforeRequestCallable] = []441 442 #: A list of functions that are called when the application context443 #: is destroyed. Since the application context is also torn down444 #: if the request ends this is the place to store code that disconnects445 #: from databases.446 #:447 #: .. versionadded:: 0.9427- self.teardown_appcontext_funcs = []448+ self.teardown_appcontext_funcs: t.List[TeardownCallable] = []449 450 #: A list of shell context processor functions that should be run451 #: when a shell context is created.452 #:453 #: .. versionadded:: 0.11433- self.shell_context_processors = []454+ self.shell_context_processors: t.List[t.Callable[[], t.Dict[str, t.Any]]] = []455 456 #: Maps registered blueprint names to blueprint objects. The457 #: dict retains the order the blueprints were registered in.458 #: Blueprints can be registered multiple times, this dict does459 #: not track how often they were attached.460 #:461 #: .. versionadded:: 0.7441- self.blueprints = {}462+ self.blueprints: t.Dict[str, "Blueprint"] = {}463 464 #: a place where extensions can store application specific state. For465 #: example this is where an extension could store database engines and466 #: similar things.2 unmodified lines469 #: case of a "Flask-Foo" extension in `flask_foo`, the key would be470 #: ``'foo'``.471 #:472 #: .. versionadded:: 0.7452- self.extensions = {}473+ self.extensions: dict = {}474 475 #: The :class:`~werkzeug.routing.Map` for this instance. You can use476 #: this to change the routing converters after the class was created477 #: but before any routes are connected. Example::34 unmodified lines512 self.add_url_rule(513 f"{self.static_url_path}/<path:filename>",514 endpoint="static",515 host=static_host,495- view_func=lambda **kw: self_ref().send_static_file(**kw),516+ view_func=lambda **kw: self_ref().send_static_file(**kw), # type: ignore # noqa: B950517 )518 519 # Set the name of the Click group in case someone wants to add520 # the app's commands to another CLI tool.521 self.cli.name = self.name522 502- def _is_setup_finished(self):523+ def _is_setup_finished(self) -> bool:524 return self.debug and self._got_first_request525 526 @locked_cached_property506- def name(self):527+ def name(self) -> str: # type: ignore528 """The name of the application. This is usually the import name529 with the difference that it's guessed from the run file if the530 import name is main. This name is used as a display name when531 Flask needs the name of the application. It can be set and overridden8 unmodified lines540 return os.path.splitext(os.path.basename(fn))[0]541 return self.import_name542 543 @property523- def propagate_exceptions(self):544+ def propagate_exceptions(self) -> bool:545 """Returns the value of the ``PROPAGATE_EXCEPTIONS`` configuration546 value in case it's set, otherwise a sensible default is returned.547 548 .. versionadded:: 0.73 unmodified lines552 return rv553 return self.testing or self.debug554 555 @property535- def preserve_context_on_exception(self):556+ def preserve_context_on_exception(self) -> bool:557 """Returns the value of the ``PRESERVE_CONTEXT_ON_EXCEPTION``558 configuration value in case it's set, otherwise a sensible default559 is returned.560 4 unmodified lines565 return rv566 return self.debug567 568 @locked_cached_property548- def logger(self):569+ def logger(self) -> logging.Logger:570 """A standard Python :class:`~logging.Logger` for the app, with571 the same name as :attr:`name`.572 573 In debug mode, the logger's :attr:`~logging.Logger.level` will18 unmodified lines592 """593 return create_logger(self)594 595 @locked_cached_property575- def jinja_env(self):596+ def jinja_env(self) -> Environment:597 """The Jinja environment used to load templates.598 599 The environment is created the first time this property is600 accessed. Changing :attr:`jinja_options` after that will have no1 unmodified line602 """603 return self.create_jinja_environment()604 605 @property585- def got_first_request(self):606+ def got_first_request(self) -> bool:607 """This attribute is set to ``True`` if the application started608 handling the first request.609 610 .. versionadded:: 0.8611 """612 return self._got_first_request613 593- def make_config(self, instance_relative=False):614+ def make_config(self, instance_relative: bool = False) -> Config:615 """Used to create the config attribute by the Flask constructor.616 The `instance_relative` parameter is passed in from the constructor617 of Flask (there named `instance_relative_config`) and indicates if618 the config should be relative to the instance path or the root path8 unmodified lines627 defaults["ENV"] = get_env()628 defaults["DEBUG"] = get_debug_flag()629 return self.config_class(root_path, defaults)630 610- def auto_find_instance_path(self):631+ def auto_find_instance_path(self) -> str:632 """Tries to locate the instance path if it was not provided to the633 constructor of the application class. It will basically calculate634 the path to a folder named ``instance`` next to your main file or635 the package.4 unmodified lines640 if prefix is None:641 return os.path.join(package_path, "instance")642 return os.path.join(prefix, "var", f"{self.name}-instance")643 623- def open_instance_resource(self, resource, mode="rb"):644+ def open_instance_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:645 """Opens a resource from the application's instance folder646 (:attr:`instance_path`). Otherwise works like647 :meth:`open_resource`. Instance resources can also be opened for648 writing.4 unmodified lines653 """654 return open(os.path.join(self.instance_path, resource), mode)655 656 @property636- def templates_auto_reload(self):657+ def templates_auto_reload(self) -> bool:658 """Reload templates when they are changed. Used by659 :meth:`create_jinja_environment`.660 661 This attribute can be configured with :data:`TEMPLATES_AUTO_RELOAD`. If6 unmodified lines668 rv = self.config["TEMPLATES_AUTO_RELOAD"]669 return rv if rv is not None else self.debug670 671 @templates_auto_reload.setter651- def templates_auto_reload(self, value):672+ def templates_auto_reload(self, value: bool) -> None:673 self.config["TEMPLATES_AUTO_RELOAD"] = value674 654- def create_jinja_environment(self):675+ def create_jinja_environment(self) -> Environment:676 """Create the Jinja environment based on :attr:`jinja_options`677 and the various Jinja-related methods of the app. Changing678 :attr:`jinja_options` after this will have no effect. Also adds679 Flask-related globals and filters to the environment.23 unmodified lines703 request=request,704 session=session,705 g=g,706 )686- rv.policies["json.dumps_function"] = json.dumps707+ rv.policies["json.dumps_function"] = json.dumps # type: ignore708 return rv709 689- def create_global_jinja_loader(self):710+ def create_global_jinja_loader(self) -> DispatchingJinjaLoader:711 """Creates the loader for the Jinja2 environment. Can be used to712 override just the loader and keeping the rest unchanged. It's713 discouraged to override this function. Instead one should override714 the :meth:`jinja_loader` function instead.4 unmodified lines719 .. versionadded:: 0.7720 """721 return DispatchingJinjaLoader(self)722 702- def select_jinja_autoescape(self, filename):723+ def select_jinja_autoescape(self, filename: str) -> bool:724 """Returns ``True`` if autoescaping should be active for the given725 template name. If no template name is given, returns `True`.726 727 .. versionadded:: 0.51 unmodified line729 if filename is None:730 return True731 return filename.endswith((".html", ".htm", ".xml", ".xhtml"))732 712- def update_template_context(self, context):733+ def update_template_context(self, context: dict) -> None:734 """Update the template context with some commonly used variables.735 This injects request, session, config and g into the template736 context as well as everything template context processors want737 to inject. Note that the as of Flask 0.6, the original values2 unmodified lines740 741 :param context: the context as a dictionary that is updated in place742 to add extra variables.743 """744+ funcs: t.Iterable[745+ TemplateContextProcessorCallable723- funcs = self.template_context_processors[None]746+ ] = self.template_context_processors[None]747 reqctx = _request_ctx_stack.top748 if reqctx is not None:749 for bp in self._request_blueprints():750 if bp in self.template_context_processors:5 unmodified lines756 # easier add new variables in context processors without breaking757 # existing views.758 context.update(orig_ctx)759 737- def make_shell_context(self):760+ def make_shell_context(self) -> dict:761 """Returns the shell context for an interactive shell for this762 application. This runs all the registered shell context763 processors.764 15 unmodified lines780 #: Default: ``'production'``781 env = ConfigAttribute("ENV")782 783 @property761- def debug(self):784+ def debug(self) -> bool:785 """Whether debug mode is enabled. When using ``flask run`` to start786 the development server, an interactive debugger will be shown for787 unhandled exceptions, and the server will be reloaded when code788 changes. This maps to the :data:`DEBUG` config key. This is8 unmodified lines797 """798 return self.config["DEBUG"]799 800 @debug.setter778- def debug(self, value):801+ def debug(self, value: bool) -> None:802 self.config["DEBUG"] = value803 self.jinja_env.auto_reload = self.templates_auto_reload804 782- def run(self, host=None, port=None, debug=None, load_dotenv=True, **options):805+ def run(806+ self,807+ host: t.Optional[str] = None,808+ port: t.Optional[int] = None,809+ debug: t.Optional[bool] = None,810+ load_dotenv: bool = True,811+ **options: t.Any,812+ ) -> None:813 """Runs the application on a local development server.814 815 Do not use ``run()`` in a production setting. It is not intended to816 meet security and performance requirements for a production server.99 unmodified lines916 917 from werkzeug.serving import run_simple918 919 try:890- run_simple(host, port, self, **options)920+ run_simple(t.cast(str, host), port, self, **options)921 finally:922 # reset the first request information if the development server923 # reset normally. This makes it possible to restart the server924 # without reloader and that stuff from an interactive shell.925 self._got_first_request = False926 897- def test_client(self, use_cookies=True, **kwargs):927+ def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> "FlaskClient":928 """Creates a test client for this application. For information929 about unit testing head over to :doc:`/testing`.930 931 Note that if you are testing for assertions or exceptions in your44 unmodified lines976 the constructor of :attr:`test_client_class`.977 """978 cls = self.test_client_class979 if cls is None:950- from .testing import FlaskClient as cls951- return cls(self, self.response_class, use_cookies=use_cookies, **kwargs)980+ from .testing import FlaskClient as cls # type: ignore981+ return cls( # type: ignore982+ self, self.response_class, use_cookies=use_cookies, **kwargs983+ )984 953- def test_cli_runner(self, **kwargs):985+ def test_cli_runner(self, **kwargs: t.Any) -> "FlaskCliRunner":986 """Create a CLI runner for testing CLI commands.987 See :ref:`testing-cli`.988 989 Returns an instance of :attr:`test_cli_runner_class`, by default4 unmodified lines994 """995 cls = self.test_cli_runner_class996 997 if cls is None:966- from .testing import FlaskCliRunner as cls998+ from .testing import FlaskCliRunner as cls # type: ignore999 968- return cls(self, **kwargs)1000+ return cls(self, **kwargs) # type: ignore1001 1002 @setupmethod971- def register_blueprint(self, blueprint, **options):1003+ def register_blueprint(self, blueprint: "Blueprint", **options: t.Any) -> None:1004 """Register a :class:`~flask.Blueprint` on the application. Keyword1005 arguments passed to this method will override the defaults set on the1006 blueprint.1007 12 unmodified lines1020 .. versionadded:: 0.71021 """1022 blueprint.register(self, options)1023 992- def iter_blueprints(self):1024+ def iter_blueprints(self) -> t.ValuesView["Blueprint"]:1025 """Iterates over all blueprints by the order they were registered.1026 1027 .. versionadded:: 0.111028 """1 unmodified line1030 1031 @setupmethod1032 def add_url_rule(1033 self,1002- rule,1003- endpoint=None,1004- view_func=None,1005- provide_automatic_options=None,1006- **options,1007- ):1034+ rule: str,1035+ endpoint: t.Optional[str] = None,1036+ view_func: t.Optional[t.Callable] = None,1037+ provide_automatic_options: t.Optional[bool] = None,1038+ **options: t.Any,1039+ ) -> None:1040 if endpoint is None:1009- endpoint = _endpoint_from_view_func(view_func)1041+ endpoint = _endpoint_from_view_func(view_func) # type: ignore1042 options["endpoint"] = endpoint1043 methods = options.pop("methods", None)1044 1045 # if the methods are not given and the view_func object knows its28 unmodified lines1074 # Add the required methods now.1075 methods |= required_methods1076 1077 rule = self.url_rule_class(rule, methods=methods, **options)1046- rule.provide_automatic_options = provide_automatic_options1078+ rule.provide_automatic_options = provide_automatic_options # type: ignore1079 1080 self.url_map.add(rule)1081 if view_func is not None:1082 old_func = self.view_functions.get(endpoint)1083 if getattr(old_func, "_flask_sync_wrapper", False):1052- old_func = old_func.__wrapped__1084+ old_func = old_func.__wrapped__ # type: ignore1085 if old_func is not None and old_func != view_func:1086 raise AssertionError(1087 "View function mapping is overwriting an existing"1088 f" endpoint function: {endpoint}"1089 )1090 self.view_functions[endpoint] = self.ensure_sync(view_func)1091 1092 @setupmethod1061- def template_filter(self, name=None):1093+ def template_filter(self, name: t.Optional[str] = None) -> t.Callable:1094 """A decorator that is used to register custom template filter.1095 You can specify a name for the filter, otherwise the function1096 name will be used. Example::1097 4 unmodified lines1102 :param name: the optional name of the filter, otherwise the1103 function name will be used.1104 """1105 1074- def decorator(f):1106+ def decorator(f: TemplateFilterCallable) -> TemplateFilterCallable:1107 self.add_template_filter(f, name=name)1108 return f1109 1110 return decorator1111 1112 @setupmethod1081- def add_template_filter(self, f, name=None):1113+ def add_template_filter(1114+ self, f: TemplateFilterCallable, name: t.Optional[str] = None1115+ ) -> None:1116 """Register a custom template filter. Works exactly like the1117 :meth:`template_filter` decorator.1118 1119 :param name: the optional name of the filter, otherwise the1 unmodified line1121 """1122 self.jinja_env.filters[name or f.__name__] = f1123 1124 @setupmethod1091- def template_test(self, name=None):1125+ def template_test(self, name: t.Optional[str] = None) -> t.Callable:1126 """A decorator that is used to register custom template test.1127 You can specify a name for the test, otherwise the function1128 name will be used. Example::1129 11 unmodified lines1141 :param name: the optional name of the test, otherwise the1142 function name will be used.1143 """1144 1111- def decorator(f):1145+ def decorator(f: TemplateTestCallable) -> TemplateTestCallable:1146 self.add_template_test(f, name=name)1147 return f1148 1149 return decorator1150 1151 @setupmethod1118- def add_template_test(self, f, name=None):1152+ def add_template_test(1153+ self, f: TemplateTestCallable, name: t.Optional[str] = None1154+ ) -> None:1155 """Register a custom template test. Works exactly like the1156 :meth:`template_test` decorator.1157 1158 .. versionadded:: 0.103 unmodified lines1162 """1163 self.jinja_env.tests[name or f.__name__] = f1164 1165 @setupmethod1130- def template_global(self, name=None):1166+ def template_global(self, name: t.Optional[str] = None) -> t.Callable:1167 """A decorator that is used to register a custom template global function.1168 You can specify a name for the global function, otherwise the function1169 name will be used. Example::1170 6 unmodified lines1177 :param name: the optional name of the global function, otherwise the1178 function name will be used.1179 """1180 1145- def decorator(f):1181+ def decorator(f: TemplateGlobalCallable) -> TemplateGlobalCallable:1182 self.add_template_global(f, name=name)1183 return f1184 1185 return decorator1186 1187 @setupmethod1152- def add_template_global(self, f, name=None):1188+ def add_template_global(1189+ self, f: TemplateGlobalCallable, name: t.Optional[str] = None1190+ ) -> None:1191 """Register a custom template global function. Works exactly like the1192 :meth:`template_global` decorator.1193 1194 .. versionadded:: 0.103 unmodified lines1198 """1199 self.jinja_env.globals[name or f.__name__] = f1200 1201 @setupmethod1164- def before_first_request(self, f):1202+ def before_first_request(self, f: BeforeRequestCallable) -> BeforeRequestCallable:1203 """Registers a function to be run before the first request to this1204 instance of the application.1205 1206 The function will be called without any arguments and its return4 unmodified lines1211 self.before_first_request_funcs.append(self.ensure_sync(f))1212 return f1213 1214 @setupmethod1177- def teardown_appcontext(self, f):1215+ def teardown_appcontext(self, f: TeardownCallable) -> TeardownCallable:1216 """Registers a function to be called when the application context1217 ends. These functions are typically also called when the request1218 context is popped.1219 24 unmodified lines1244 self.teardown_appcontext_funcs.append(self.ensure_sync(f))1245 return f1246 1247 @setupmethod1210- def shell_context_processor(self, f):1248+ def shell_context_processor(self, f: t.Callable) -> t.Callable:1249 """Registers a shell context processor function.1250 1251 .. versionadded:: 0.111252 """1253 self.shell_context_processors.append(f)1254 return f1255 1218- def _find_error_handler(self, e):1256+ def _find_error_handler(self, e: Exception) -> t.Optional[ErrorHandlerCallable]:1257 """Return a registered error handler for an exception in this order:1258 blueprint handler for a specific code, app handler for a specific code,1259 blueprint handler for an exception class, app handler for an exception1260 class, or ``None`` if a suitable handler is not found.11 unmodified lines1272 handler = handler_map.get(cls)1273 1274 if handler is not None:1275 return handler1276+ return None1277 1239- def handle_http_exception(self, e):1278+ def handle_http_exception(1279+ self, e: HTTPException1280+ ) -> t.Union[HTTPException, ResponseReturnValue]:1281 """Handles an HTTP exception. By default this will invoke the1282 registered error handlers and fall back to returning the1283 exception as response.1284 24 unmodified lines1309 if handler is None:1310 return e1311 return handler(e)1312 1272- def trap_http_exception(self, e):1313+ def trap_http_exception(self, e: Exception) -> bool:1314 """Checks if an HTTP exception should be trapped or not. By default1315 this will return ``False`` for all exceptions except for a bad request1316 key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It1317 also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.26 unmodified lines1344 return isinstance(e, BadRequest)1345 1346 return False1347 1307- def handle_user_exception(self, e):1348+ def handle_user_exception(1349+ self, e: Exception1350+ ) -> t.Union[HTTPException, ResponseReturnValue]:1351 """This method is called whenever an exception occurs that1352 should be handled. A special case is :class:`~werkzeug1353 .exceptions.HTTPException` which is forwarded to the1354 :meth:`handle_http_exception` method. This function will either21 unmodified lines1376 raise1377 1378 return handler(e)1379 1337- def handle_exception(self, e):1380+ def handle_exception(self, e: Exception) -> Response:1381 """Handle an exception that did not have an error handler1382 associated with it, or that was raised from an error handler.1383 This always causes a 500 ``InternalServerError``.1384 31 unmodified lines1416 1417 raise e1418 1419 self.log_exception(exc_info)1420+ server_error: t.Union[InternalServerError, ResponseReturnValue]1421 server_error = InternalServerError(original_exception=e)1422 handler = self._find_error_handler(server_error)1423 1424 if handler is not None:1425 server_error = handler(server_error)1426 1427 return self.finalize_request(server_error, from_error_handler=True)1428 1385- def log_exception(self, exc_info):1429+ def log_exception(1430+ self,1431+ exc_info: t.Union[1432+ t.Tuple[type, BaseException, TracebackType], t.Tuple[None, None, None]1433+ ],1434+ ) -> None:1435 """Logs an exception. This is called by :meth:`handle_exception`1436 if debugging is disabled and right before the handler is called.1437 The default implementation logs the exception as error on the1438 :attr:`logger`.3 unmodified lines1442 self.logger.error(1443 f"Exception on {request.path} [{request.method}]", exc_info=exc_info1444 )1445 1397- def raise_routing_exception(self, request):1446+ def raise_routing_exception(self, request: Request) -> t.NoReturn:1447 """Exceptions that are recording during routing are reraised with1448 this method. During debug we are not reraising redirect requests1449 for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising1450 a different error instead to help debug situations.4 unmodified lines1455 not self.debug1456 or not isinstance(request.routing_exception, RequestRedirect)1457 or request.method in ("GET", "HEAD", "OPTIONS")1458 ):1410- raise request.routing_exception1459+ raise request.routing_exception # type: ignore1460 1461 from .debughelpers import FormDataRoutingRedirect1462 1463 raise FormDataRoutingRedirect(request)1464 1416- def dispatch_request(self):1465+ def dispatch_request(self) -> ResponseReturnValue:1466 """Does the request dispatching. Matches the URL and returns the1467 return value of the view or error handler. This does not have to1468 be a response object. In order to convert the return value to a1469 proper response object, call :func:`make_response`.15 unmodified lines1485 return self.make_default_options_response()1486 # otherwise dispatch to the handler for that endpoint1487 return self.view_functions[rule.endpoint](**req.view_args)1488 1440- def full_dispatch_request(self):1489+ def full_dispatch_request(self) -> Response:1490 """Dispatches the request and on top of that performs request1491 pre and postprocessing as well as HTTP exception catching and1492 error handling.1493 8 unmodified lines1502 except Exception as e:1503 rv = self.handle_user_exception(e)1504 return self.finalize_request(rv)1505 1457- def finalize_request(self, rv, from_error_handler=False):1506+ def finalize_request(1507+ self,1508+ rv: t.Union[ResponseReturnValue, HTTPException],1509+ from_error_handler: bool = False,1510+ ) -> Response:1511 """Given the return value from a view function this finalizes1512 the request by converting it into a response and invoking the1513 postprocessing functions. This is invoked for both normal1514 request dispatching as well as error handlers.16 unmodified lines1531 "Request finalizing failed with an error while handling an error"1532 )1533 return response1534 1482- def try_trigger_before_first_request_functions(self):1535+ def try_trigger_before_first_request_functions(self) -> None:1536 """Called before each request and will ensure that it triggers1537 the :attr:`before_first_request_funcs` and only exactly once per1538 application instance (which means process usually).1539 7 unmodified lines1547 for func in self.before_first_request_funcs:1548 func()1549 self._got_first_request = True1550 1498- def make_default_options_response(self):1551+ def make_default_options_response(self) -> Response:1552 """This method is called to create the default ``OPTIONS`` response.1553 This can be changed through subclassing to change the default1554 behavior of ``OPTIONS`` responses.1555 4 unmodified lines1560 rv = self.response_class()1561 rv.allow.update(methods)1562 return rv1563 1511- def should_ignore_error(self, error):1564+ def should_ignore_error(self, error: t.Optional[BaseException]) -> bool:1565 """This is called to figure out if an error should be ignored1566 or not as far as the teardown system is concerned. If this1567 function returns ``True`` then the teardown handlers will not be1568 passed the error.1 unmodified line1570 .. versionadded:: 0.101571 """1572 return False1573 1521- def ensure_sync(self, func):1574+ def ensure_sync(self, func: t.Callable) -> t.Callable:1575 """Ensure that the function is synchronous for WSGI workers.1576 Plain ``def`` functions are returned as-is. ``async def``1577 functions are wrapped to run and wait for the response.1578 5 unmodified lines1584 return run_async(func)1585 1586 return func1587 1535- def make_response(self, rv):1588+ def make_response(self, rv: ResponseReturnValue) -> Response:1589 """Convert the return value from a view function to an instance of1590 :attr:`response_class`.1591 1592 :param rv: the return value from the view function. The view function79 unmodified lines1672 elif isinstance(rv, BaseResponse) or callable(rv):1673 # evaluate a WSGI callable, or coerce a different response1674 # class to the correct type1675 try:1623- rv = self.response_class.force_type(rv, request.environ)1676+ rv = self.response_class.force_type(rv, request.environ) # type: ignore # noqa: B9501677 except TypeError as e:1678 raise TypeError(1679 f"{e}\nThe view function did not return a valid"1680 " response. The return type must be a string,"7 unmodified lines1688 " dict, tuple, Response instance, or WSGI"1689 f" callable, but it was a {type(rv).__name__}."1690 )1691 1692+ rv = t.cast(Response, rv)1693 # prefer the status if it was provided1694 if status is not None:1695 if isinstance(status, (str, bytes, bytearray)):1642- rv.status = status1696+ rv.status = status # type: ignore1697 else:1698 rv.status_code = status1699 1700 # extend existing headers with provided headers1 unmodified line1702 rv.headers.update(headers)1703 1704 return rv1705 1652- def create_url_adapter(self, request):1706+ def create_url_adapter(1707+ self, request: t.Optional[Request]1708+ ) -> t.Optional[MapAdapter]:1709 """Creates a URL adapter for the given request. The URL adapter1710 is created at a point where the request context is not yet set1711 up so the request is passed explicitly.1712 29 unmodified lines1742 script_name=self.config["APPLICATION_ROOT"],1743 url_scheme=self.config["PREFERRED_URL_SCHEME"],1744 )1745 1746+ return None1747+1690- def inject_url_defaults(self, endpoint, values):1748+ def inject_url_defaults(self, endpoint: str, values: dict) -> None:1749 """Injects the URL defaults for the given endpoint directly into1750 the values dictionary passed. This is used internally and1751 automatically called on URL building.1752 1753 .. versionadded:: 0.71754 """1697- funcs = self.url_default_functions[None]1755+ funcs: t.Iterable[URLDefaultCallable] = self.url_default_functions[None]1756 if "." in endpoint:1757 bp = endpoint.rsplit(".", 1)[0]1758 funcs = chain(funcs, self.url_default_functions[bp])1759 for func in funcs:1760 func(endpoint, values)1761 1704- def handle_url_build_error(self, error, endpoint, values):1762+ def handle_url_build_error(1763+ self, error: Exception, endpoint: str, values: dict1764+ ) -> str:1765 """Handle :class:`~werkzeug.routing.BuildError` on1766 :meth:`url_for`.1767 """1768 for handler in self.url_build_error_handlers:12 unmodified lines1781 raise1782 1783 raise error1784 1725- def preprocess_request(self):1785+ def preprocess_request(self) -> t.Optional[ResponseReturnValue]:1786 """Called before the request is dispatched. Calls1787 :attr:`url_value_preprocessors` registered with the app and the1788 current blueprint (if any). Then calls :attr:`before_request_funcs`1789 registered with the app and the blueprint.2 unmodified lines1792 value is handled as if it was the return value from the view, and1793 further request handling is stopped.1794 """1795 1736- funcs = self.url_value_preprocessors[None]1796+ funcs: t.Iterable[URLValuePreprocessorCallable] = self.url_value_preprocessors[1797+ None1798+ ]1799 for bp in self._request_blueprints():1800 if bp in self.url_value_preprocessors:1801 funcs = chain(funcs, self.url_value_preprocessors[bp])1802 for func in funcs:1803 func(request.endpoint, request.view_args)1804 1743- funcs = self.before_request_funcs[None]1805+ funcs: t.Iterable[BeforeRequestCallable] = self.before_request_funcs[None]1806 for bp in self._request_blueprints():1807 if bp in self.before_request_funcs:1808 funcs = chain(funcs, self.before_request_funcs[bp])1809 for func in funcs:1810 rv = func()1811 if rv is not None:1812 return rv1813 1814+ return None1815+1752- def process_response(self, response):1816+ def process_response(self, response: Response) -> Response:1817 """Can be overridden in order to modify the response object1818 before it's sent to the WSGI server. By default this will1819 call all the :meth:`after_request` decorated functions.1820 5 unmodified lines1826 :return: a new response object or the same, has to be an1827 instance of :attr:`response_class`.1828 """1829 ctx = _request_ctx_stack.top1766- funcs = ctx._after_request_functions1830+ funcs: t.Iterable[AfterRequestCallable] = ctx._after_request_functions1831 for bp in self._request_blueprints():1832 if bp in self.after_request_funcs:1833 funcs = chain(funcs, reversed(self.after_request_funcs[bp]))1834 if None in self.after_request_funcs:3 unmodified lines1838 if not self.session_interface.is_null_session(ctx.session):1839 self.session_interface.save_session(self, ctx.session, response)1840 return response1841 1778- def do_teardown_request(self, exc=_sentinel):1842+ def do_teardown_request(1843+ self, exc: t.Optional[BaseException] = _sentinel # type: ignore1844+ ) -> None:1845 """Called after the request is dispatched and the response is1846 returned, right before the request context is popped.1847 1848 This calls all functions decorated with14 unmodified lines1863 Added the ``exc`` argument.1864 """1865 if exc is _sentinel:1866 exc = sys.exc_info()[1]1801- funcs = reversed(self.teardown_request_funcs[None])1867+ funcs: t.Iterable[TeardownCallable] = reversed(1868+ self.teardown_request_funcs[None]1869+ )1870 for bp in self._request_blueprints():1871 if bp in self.teardown_request_funcs:1872 funcs = chain(funcs, reversed(self.teardown_request_funcs[bp]))1873 for func in funcs:1874 func(exc)1875 request_tearing_down.send(self, exc=exc)1876 1809- def do_teardown_appcontext(self, exc=_sentinel):1877+ def do_teardown_appcontext(1878+ self, exc: t.Optional[BaseException] = _sentinel # type: ignore1879+ ) -> None:1880 """Called right before the application context is popped.1881 1882 When handling a request, the application context is popped1883 after the request context. See :meth:`do_teardown_request`.12 unmodified lines1896 for func in reversed(self.teardown_appcontext_funcs):1897 func(exc)1898 appcontext_tearing_down.send(self, exc=exc)1899 1830- def app_context(self):1900+ def app_context(self) -> AppContext:1901 """Create an :class:`~flask.ctx.AppContext`. Use as a ``with``1902 block to push the context, which will make :data:`current_app`1903 point at this application.1904 12 unmodified lines1917 .. versionadded:: 0.91918 """1919 return AppContext(self)1920 1851- def request_context(self, environ):1921+ def request_context(self, environ: dict) -> RequestContext:1922 """Create a :class:`~flask.ctx.RequestContext` representing a1923 WSGI environment. Use a ``with`` block to push the context,1924 which will make :data:`request` point at this request.1925 7 unmodified lines1933 :param environ: a WSGI environment1934 """1935 return RequestContext(self, environ)1936 1867- def test_request_context(self, *args, **kwargs):1937+ def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> RequestContext:1938 """Create a :class:`~flask.ctx.RequestContext` for a WSGI1939 environment created from the given values. This is mostly useful1940 during testing, where you may want to run a function that uses1941 request data without dispatching a full request.47 unmodified lines1989 return self.request_context(builder.get_environ())1990 finally:1991 builder.close()1992 1923- def wsgi_app(self, environ, start_response):1993+ def wsgi_app(self, environ: dict, start_response: t.Callable) -> t.Any:1994 """The actual WSGI application. This is not implemented in1995 :meth:`__call__` so that middlewares can be applied without1996 losing a reference to the app object. Instead of doing this::1997 17 unmodified lines2015 a list of headers, and an optional exception context to2016 start the response.2017 """2018 ctx = self.request_context(environ)1949- error = None2019+ error: t.Optional[BaseException] = None2020 try:2021 try:2022 ctx.push()2023 response = self.full_dispatch_request()8 unmodified lines2032 if self.should_ignore_error(error):2033 error = None2034 ctx.auto_pop(error)2035 1966- def __call__(self, environ, start_response):2036+ def __call__(self, environ: dict, start_response: t.Callable) -> t.Any:2037 """The WSGI server calls the Flask application object as the2038 WSGI application. This calls :meth:`wsgi_app`, which can be2039 wrapped to apply middleware.2040 """2041 return self.wsgi_app(environ, start_response)2042 1973- def _request_blueprints(self):2043+ def _request_blueprints(self) -> t.Iterable[str]:2044 if _request_ctx_stack.top.request.blueprint is None:2045 return []2046 else:2047 return reversed(_request_ctx_stack.top.request.blueprint.split("."))modified:src/flask/blueprints.py+93 added-45 removed
1+import typing as t2 from collections import defaultdict3 from functools import update_wrapper4 5 from .scaffold import _endpoint_from_view_func6 from .scaffold import _sentinel7 from .scaffold import Scaffold8+from .typing import AfterRequestCallable9+from .typing import BeforeRequestCallable10+from .typing import ErrorHandlerCallable11+from .typing import TeardownCallable12+from .typing import TemplateContextProcessorCallable13+from .typing import TemplateFilterCallable14+from .typing import TemplateGlobalCallable15+from .typing import TemplateTestCallable16+from .typing import URLDefaultCallable17+from .typing import URLValuePreprocessorCallable18 19+if t.TYPE_CHECKING:20+ from .app import Flask21 22+DeferredSetupFunction = t.Callable[["BlueprintSetupState"], t.Callable]23+24+25 class BlueprintSetupState:26 """Temporary holder object for registering a blueprint with the27 application. An instance of this class is created by the28 :meth:`~flask.Blueprint.make_setup_state` method and later passed29 to all register callback functions.30 """31 16- def __init__(self, blueprint, app, options, first_registration):32+ def __init__(33+ self,34+ blueprint: "Blueprint",35+ app: "Flask",36+ options: t.Any,37+ first_registration: bool,38+ ) -> None:39 #: a reference to the current application40 self.app = app41 42 #: a reference to the blueprint that created this setup state.30 unmodified lines73 #: URL that was defined with the blueprint.74 self.url_defaults = dict(self.blueprint.url_values_defaults)75 self.url_defaults.update(self.options.get("url_defaults", ()))76 55- def add_url_rule(self, rule, endpoint=None, view_func=None, **options):77+ def add_url_rule(78+ self,79+ rule: str,80+ endpoint: t.Optional[str] = None,81+ view_func: t.Optional[t.Callable] = None,82+ **options: t.Any,83+ ) -> None:84 """A helper method to register a rule (and optionally a view function)85 to the application. The endpoint is automatically prefixed with the86 blueprint's name.87 """3 unmodified lines91 else:92 rule = self.url_prefix93 options.setdefault("subdomain", self.subdomain)94 if endpoint is None:67- endpoint = _endpoint_from_view_func(view_func)95+ endpoint = _endpoint_from_view_func(view_func) # type: ignore96 defaults = self.url_defaults97 if "defaults" in options:98 defaults = dict(defaults, **options.pop("defaults"))99 self.app.add_url_rule(69 unmodified lines169 json_decoder = None170 171 def __init__(172 self,145- name,146- import_name,147- static_folder=None,148- static_url_path=None,149- template_folder=None,150- url_prefix=None,151- subdomain=None,152- url_defaults=None,153- root_path=None,154- cli_group=_sentinel,173+ name: str,174+ import_name: str,175+ static_folder: t.Optional[str] = None,176+ static_url_path: t.Optional[str] = None,177+ template_folder: t.Optional[str] = None,178+ url_prefix: t.Optional[str] = None,179+ subdomain: t.Optional[str] = None,180+ url_defaults: t.Optional[dict] = None,181+ root_path: t.Optional[str] = None,182+ cli_group: t.Optional[str] = _sentinel, # type: ignore183 ):184 super().__init__(185 import_name=import_name,186 static_folder=static_folder,3 unmodified lines190 )191 self.name = name192 self.url_prefix = url_prefix193 self.subdomain = subdomain166- self.deferred_functions = []194+ self.deferred_functions: t.List[DeferredSetupFunction] = []195 196 if url_defaults is None:197 url_defaults = {}198 199 self.url_values_defaults = url_defaults200 self.cli_group = cli_group173- self._blueprints = []201+ self._blueprints: t.List[t.Tuple["Blueprint", dict]] = []202 175- def _is_setup_finished(self):203+ def _is_setup_finished(self) -> bool:204 return self.warn_on_modifications and self._got_registered_once205 178- def record(self, func):206+ def record(self, func: t.Callable) -> None:207 """Registers a function that is called when the blueprint is208 registered on the application. This function is called with the209 state as argument as returned by the :meth:`make_setup_state`210 method.9 unmodified lines220 )221 )222 self.deferred_functions.append(func)223 196- def record_once(self, func):224+ def record_once(self, func: t.Callable) -> None:225 """Works like :meth:`record` but wraps the function in another226 function that will ensure the function is only called once. If the227 blueprint is registered a second time on the application, the228 function passed is not called.229 """230 203- def wrapper(state):231+ def wrapper(state: BlueprintSetupState) -> None:232 if state.first_registration:233 func(state)234 235 return self.record(update_wrapper(wrapper, func))236 209- def make_setup_state(self, app, options, first_registration=False):237+ def make_setup_state(238+ self, app: "Flask", options: dict, first_registration: bool = False239+ ) -> BlueprintSetupState:240 """Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`241 object that is later passed to the register callback functions.242 Subclasses can override this to return a subclass of the setup state.243 """244 return BlueprintSetupState(self, app, options, first_registration)245 216- def register_blueprint(self, blueprint, **options):246+ def register_blueprint(self, blueprint: "Blueprint", **options: t.Any) -> None:247 """Register a :class:`~flask.Blueprint` on this blueprint. Keyword248 arguments passed to this method will override the defaults set249 on the blueprint.250 251 .. versionadded:: 2.0252 """253 self._blueprints.append((blueprint, options))254 225- def register(self, app, options):255+ def register(self, app: "Flask", options: dict) -> None:256 """Called by :meth:`Flask.register_blueprint` to register all257 views and callbacks registered on the blueprint with the258 application. Creates a :class:`.BlueprintSetupState` and calls259 each :meth:`record` callbackwith it.96 unmodified lines356 bp_options["url_prefix"] = url_prefix357 bp_options["name_prefix"] = options.get("name_prefix", "") + self.name + "."358 blueprint.register(app, bp_options)359 330- def add_url_rule(self, rule, endpoint=None, view_func=None, **options):360+ def add_url_rule(361+ self,362+ rule: str,363+ endpoint: t.Optional[str] = None,364+ view_func: t.Optional[t.Callable] = None,365+ **options: t.Any,366+ ) -> None:367 """Like :meth:`Flask.add_url_rule` but for a blueprint. The endpoint for368 the :func:`url_for` function is prefixed with the name of the blueprint.369 """370 if endpoint:3 unmodified lines374 "." not in view_func.__name__375 ), "Blueprint view function name should not contain dots"376 self.record(lambda s: s.add_url_rule(rule, endpoint, view_func, **options))377 342- def app_template_filter(self, name=None):378+ def app_template_filter(self, name: t.Optional[str] = None) -> t.Callable:379 """Register a custom template filter, available application wide. Like380 :meth:`Flask.template_filter` but for a blueprint.381 382 :param name: the optional name of the filter, otherwise the383 function name will be used.384 """385 350- def decorator(f):386+ def decorator(f: TemplateFilterCallable) -> TemplateFilterCallable:387 self.add_app_template_filter(f, name=name)388 return f389 390 return decorator391 356- def add_app_template_filter(self, f, name=None):392+ def add_app_template_filter(393+ self, f: TemplateFilterCallable, name: t.Optional[str] = None394+ ) -> None:395 """Register a custom template filter, available application wide. Like396 :meth:`Flask.add_template_filter` but for a blueprint. Works exactly397 like the :meth:`app_template_filter` decorator.398 399 :param name: the optional name of the filter, otherwise the400 function name will be used.401 """402 365- def register_template(state):403+ def register_template(state: BlueprintSetupState) -> None:404 state.app.jinja_env.filters[name or f.__name__] = f405 406 self.record_once(register_template)407 370- def app_template_test(self, name=None):408+ def app_template_test(self, name: t.Optional[str] = None) -> t.Callable:409 """Register a custom template test, available application wide. Like410 :meth:`Flask.template_test` but for a blueprint.411 412 .. versionadded:: 0.101 unmodified line414 :param name: the optional name of the test, otherwise the415 function name will be used.416 """417 380- def decorator(f):418+ def decorator(f: TemplateTestCallable) -> TemplateTestCallable:419 self.add_app_template_test(f, name=name)420 return f421 422 return decorator423 386- def add_app_template_test(self, f, name=None):424+ def add_app_template_test(425+ self, f: TemplateTestCallable, name: t.Optional[str] = None426+ ) -> None:427 """Register a custom template test, available application wide. Like428 :meth:`Flask.add_template_test` but for a blueprint. Works exactly429 like the :meth:`app_template_test` decorator.430 2 unmodified lines433 :param name: the optional name of the test, otherwise the434 function name will be used.435 """436 397- def register_template(state):437+ def register_template(state: BlueprintSetupState) -> None:438 state.app.jinja_env.tests[name or f.__name__] = f439 440 self.record_once(register_template)441 402- def app_template_global(self, name=None):442+ def app_template_global(self, name: t.Optional[str] = None) -> t.Callable:443 """Register a custom template global, available application wide. Like444 :meth:`Flask.template_global` but for a blueprint.445 446 .. versionadded:: 0.101 unmodified line448 :param name: the optional name of the global, otherwise the449 function name will be used.450 """451 412- def decorator(f):452+ def decorator(f: TemplateGlobalCallable) -> TemplateGlobalCallable:453 self.add_app_template_global(f, name=name)454 return f455 456 return decorator457 418- def add_app_template_global(self, f, name=None):458+ def add_app_template_global(459+ self, f: TemplateGlobalCallable, name: t.Optional[str] = None460+ ) -> None:461 """Register a custom template global, available application wide. Like462 :meth:`Flask.add_template_global` but for a blueprint. Works exactly463 like the :meth:`app_template_global` decorator.464 2 unmodified lines467 :param name: the optional name of the global, otherwise the468 function name will be used.469 """470 429- def register_template(state):471+ def register_template(state: BlueprintSetupState) -> None:472 state.app.jinja_env.globals[name or f.__name__] = f473 474 self.record_once(register_template)475 434- def before_app_request(self, f):476+ def before_app_request(self, f: BeforeRequestCallable) -> BeforeRequestCallable:477 """Like :meth:`Flask.before_request`. Such a function is executed478 before each request, even if outside of a blueprint.479 """480 self.record_once(2 unmodified lines483 )484 )485 return f486 445- def before_app_first_request(self, f):487+ def before_app_first_request(488+ self, f: BeforeRequestCallable489+ ) -> BeforeRequestCallable:490 """Like :meth:`Flask.before_first_request`. Such a function is491 executed before the first request to the application.492 """493 self.record_once(494 lambda s: s.app.before_first_request_funcs.append(s.app.ensure_sync(f))495 )496 return f497 454- def after_app_request(self, f):498+ def after_app_request(self, f: AfterRequestCallable) -> AfterRequestCallable:499 """Like :meth:`Flask.after_request` but for a blueprint. Such a function500 is executed after each request, even if outside of the blueprint.501 """502 self.record_once(2 unmodified lines505 )506 )507 return f508 465- def teardown_app_request(self, f):509+ def teardown_app_request(self, f: TeardownCallable) -> TeardownCallable:510 """Like :meth:`Flask.teardown_request` but for a blueprint. Such a511 function is executed when tearing down each request, even if outside of512 the blueprint.513 """1 unmodified line515 lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)516 )517 return f518 475- def app_context_processor(self, f):519+ def app_context_processor(520+ self, f: TemplateContextProcessorCallable521+ ) -> TemplateContextProcessorCallable:522 """Like :meth:`Flask.context_processor` but for a blueprint. Such a523 function is executed each request, even if outside of the blueprint.524 """525 self.record_once(526 lambda s: s.app.template_context_processors.setdefault(None, []).append(f)527 )528 return f529 484- def app_errorhandler(self, code):530+ def app_errorhandler(self, code: t.Union[t.Type[Exception], int]) -> t.Callable:531 """Like :meth:`Flask.errorhandler` but for a blueprint. This532 handler is used for all requests, even if outside of the blueprint.533 """534 489- def decorator(f):535+ def decorator(f: ErrorHandlerCallable) -> ErrorHandlerCallable:536 self.record_once(lambda s: s.app.errorhandler(code)(f))537 return f538 539 return decorator540 495- def app_url_value_preprocessor(self, f):541+ def app_url_value_preprocessor(542+ self, f: URLValuePreprocessorCallable543+ ) -> URLValuePreprocessorCallable:544 """Same as :meth:`url_value_preprocessor` but application wide."""545 self.record_once(546 lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)547 )548 return f549 502- def app_url_defaults(self, f):550+ def app_url_defaults(self, f: URLDefaultCallable) -> URLDefaultCallable:551 """Same as :meth:`url_defaults` but application wide."""552 self.record_once(553 lambda s: s.app.url_default_functions.setdefault(None, []).append(f)554 )555 return f556 509- def ensure_sync(self, f):557+ def ensure_sync(self, f: t.Callable) -> t.Callable:558 """Ensure the function is synchronous.559 560 Override if you would like custom async to sync behaviour in561 this blueprint. Otherwise the app's5 unmodified linesmodified:src/flask/cli.py+10 added-7 removed
25 unmodified lines26 27 try:28 import ssl29 except ImportError:30- ssl = None30+ ssl = None # type: ignore31 32 33 class NoAppException(click.UsageError):34 """Raised if an application cannot be found or loaded."""824 unmodified lines859 860 861 @click.command("shell", short_help="Run a shell in the app context.")862 @with_appcontext863-def shell_command():863+def shell_command() -> None:864 """Run an interactive Python shell in the context of a given865 Flask application. The application will populate the default866 namespace of this shell according to its configuration.867 8 unmodified lines876 f"Python {sys.version} on {sys.platform}\n"877 f"App: {app.import_name} [{app.env}]\n"878 f"Instance: {app.instance_path}"879 )880- ctx = {}880+ ctx: dict = {}881 882 # Support the regular Python interpreter startup script if someone883 # is using it.884 startup = os.environ.get("PYTHONSTARTUP")36 unmodified lines921 ),922 )923 @click.option("--all-methods", is_flag=True, help="Show HEAD and OPTIONS methods.")924 @with_appcontext925-def routes_command(sort, all_methods):925+def routes_command(sort: str, all_methods: bool) -> None:926 """Show all registered routes with endpoints and methods."""927 928 rules = list(current_app.url_map.iter_rules())929 if not rules:4 unmodified lines934 935 if sort in ("endpoint", "rule"):936 rules = sorted(rules, key=attrgetter(sort))937 elif sort == "methods":938- rules = sorted(rules, key=lambda rule: sorted(rule.methods))938+ rules = sorted(rules, key=lambda rule: sorted(rule.methods)) # type: ignore939 940- rule_methods = [", ".join(sorted(rule.methods - ignored_methods)) for rule in rules]940+ rule_methods = [941+ ", ".join(sorted(rule.methods - ignored_methods)) # type: ignore942+ for rule in rules943+ ]944 945 headers = ("Endpoint", "Methods", "Rule")946 widths = (947 max(len(rule.endpoint) for rule in rules),29 unmodified lines977 )978 )979 980 978-def main():981+def main() -> None:982 # TODO omit sys.argv once https://github.com/pallets/click/issues/536 is fixed983 cli.main(args=sys.argv[1:])984 985 2 unmodified linesmodified:src/flask/config.py+28 added-26 removed
1 import errno2 import os3 import types4+import typing as t5 6 from werkzeug.utils import import_string7 8 9 class ConfigAttribute:10 """Makes an attribute forward to the config"""11 11- def __init__(self, name, get_converter=None):12+ def __init__(self, name: str, get_converter: t.Optional[t.Callable] = None) -> None:13 self.__name__ = name14 self.get_converter = get_converter15 15- def __get__(self, obj, type=None):16+ def __get__(self, obj: t.Any, owner: t.Any = None) -> t.Any:17 if obj is None:18 return self19 rv = obj.config[self.__name__]20 if self.get_converter is not None:21 rv = self.get_converter(rv)22 return rv23 23- def __set__(self, obj, value):24+ def __set__(self, obj: t.Any, value: t.Any) -> None:25 obj.config[self.__name__] = value26 27 28 class Config(dict):39 unmodified lines68 the application's :attr:`~flask.Flask.root_path`.69 :param defaults: an optional dictionary of default values70 """71 71- def __init__(self, root_path, defaults=None):72+ def __init__(self, root_path: str, defaults: t.Optional[dict] = None) -> None:73 dict.__init__(self, defaults or {})74 self.root_path = root_path75 75- def from_envvar(self, variable_name, silent=False):76+ def from_envvar(self, variable_name: str, silent: bool = False) -> bool:77 """Loads a configuration from an environment variable pointing to78 a configuration file. This is basically just a shortcut with nicer79 error messages for this line of code::80 15 unmodified lines96 " file"97 )98 return self.from_pyfile(rv, silent=silent)99 99- def from_pyfile(self, filename, silent=False):100+ def from_pyfile(self, filename: str, silent: bool = False) -> bool:101 """Updates the values in the config from a Python file. This function102 behaves as if the file was imported as module with the103 :meth:`from_object` function.104 19 unmodified lines124 raise125 self.from_object(d)126 return True127 127- def from_object(self, obj):128+ def from_object(self, obj: t.Union[object, str]) -> None:129 """Updates the values from the given object. An object can be of one130 of the following two types:131 132 - a string: in this case the object with that name will be imported29 unmodified lines162 for key in dir(obj):163 if key.isupper():164 self[key] = getattr(obj, key)165 165- def from_file(self, filename, load, silent=False):166+ def from_file(167+ self,168+ filename: str,169+ load: t.Callable[[t.IO[t.Any]], t.Mapping],170+ silent: bool = False,171+ ) -> bool:172 """Update the values in the config from a file that is loaded173 using the ``load`` parameter. The loaded data is passed to the174 :meth:`from_mapping` method.175 25 unmodified lines201 raise202 203 return self.from_mapping(obj)204 199- def from_mapping(self, *mapping, **kwargs):205+ def from_mapping(206+ self, mapping: t.Optional[t.Mapping[str, t.Any]] = None, **kwargs: t.Any207+ ) -> bool:208 """Updates the config like :meth:`update` ignoring items with non-upper209 keys.210 211 .. versionadded:: 0.11212 """205- mappings = []206- if len(mapping) == 1:207- if hasattr(mapping[0], "items"):208- mappings.append(mapping[0].items())209- else:210- mappings.append(mapping[0])211- elif len(mapping) > 1:212- raise TypeError(213- f"expected at most 1 positional argument, got {len(mapping)}"214- )215- mappings.append(kwargs.items())216- for mapping in mappings:217- for (key, value) in mapping:218- if key.isupper():219- self[key] = value213+ mappings: t.Dict[str, t.Any] = {}214+ if mapping is not None:215+ mappings.update(mapping)216+ mappings.update(kwargs)217+ for key, value in mappings.items():218+ if key.isupper():219+ self[key] = value220 return True221 222- def get_namespace(self, namespace, lowercase=True, trim_namespace=True):222+ def get_namespace(223+ self, namespace: str, lowercase: bool = True, trim_namespace: bool = True224+ ) -> t.Dict[str, t.Any]:225 """Returns a dictionary containing a subset of configuration options226 that match the specified namespace/prefix. Example usage::227 228 app.config['IMAGE_STORE_TYPE'] = 'fs'32 unmodified lines261 key = key.lower()262 rv[key] = v263 return rv264 263- def __repr__(self):265+ def __repr__(self) -> str:266 return f"<{type(self).__name__} {dict.__repr__(self)}>"modified:src/flask/ctx.py+49 added-31 removed
1 import sys2+import typing as t3 from functools import update_wrapper4+from types import TracebackType5 6 from werkzeug.exceptions import HTTPException7 8 from .globals import _app_ctx_stack9 from .globals import _request_ctx_stack10 from .signals import appcontext_popped11 from .signals import appcontext_pushed12+from .typing import AfterRequestCallable13 14+if t.TYPE_CHECKING:15+ from .app import Flask16+ from .sessions import SessionMixin17+ from .wrappers import Request18 19+20 # a singleton sentinel value for parameter defaults21 _sentinel = object()22 23 16 unmodified lines40 41 .. versionadded:: 0.1042 """43 36- def get(self, name, default=None):44+ def get(self, name: str, default: t.Optional[t.Any] = None) -> t.Any:45 """Get an attribute by name, or a default value. Like46 :meth:`dict.get`.47 48 :param name: Name of attribute to get.2 unmodified lines51 .. versionadded:: 0.1052 """53 return self.__dict__.get(name, default)54 47- def pop(self, name, default=_sentinel):55+ def pop(self, name: str, default: t.Any = _sentinel) -> t.Any:56 """Get and remove an attribute by name. Like :meth:`dict.pop`.57 58 :param name: Name of attribute to pop.59 :param default: Value to return if the attribute is not present,5 unmodified lines65 return self.__dict__.pop(name)66 else:67 return self.__dict__.pop(name, default)68 61- def setdefault(self, name, default=None):69+ def setdefault(self, name: str, default: t.Any = None) -> t.Any:70 """Get the value of an attribute if it is present, otherwise71 set and return a default value. Like :meth:`dict.setdefault`.72 73 :param name: Name of attribute to get.3 unmodified lines77 .. versionadded:: 0.1178 """79 return self.__dict__.setdefault(name, default)80 73- def __contains__(self, item):81+ def __contains__(self, item: t.Any) -> bool:82 return item in self.__dict__83 76- def __iter__(self):84+ def __iter__(self) -> t.Iterator:85 return iter(self.__dict__)86 79- def __repr__(self):87+ def __repr__(self) -> str:88 top = _app_ctx_stack.top89 if top is not None:90 return f"<flask.g of {top.app.name!r}>"91 return object.__repr__(self)92 93 86-def after_this_request(f):94+def after_this_request(f: AfterRequestCallable) -> AfterRequestCallable:95 """Executes a function after this request. This is useful to modify96 response objects. The function is passed the response object and has97 to return the same or a new one.98 16 unmodified lines115 _request_ctx_stack.top._after_request_functions.append(f)116 return f117 118 111-def copy_current_request_context(f):119+def copy_current_request_context(f: t.Callable) -> t.Callable:120 """A helper function that decorates a function to retain the current121 request context. This is useful when working with greenlets. The moment122 the function is decorated a copy of the request context is created and123 then pushed when the function is called. The current session is also31 unmodified lines155 156 return update_wrapper(wrapper, f)157 158 151-def has_request_context():159+def has_request_context() -> bool:160 """If you have code that wants to test if a request context is there or161 not this function can be used. For instance, you may want to take advantage162 of request information if the request object is available, but fail163 silently if it is unavailable.23 unmodified lines187 """188 return _request_ctx_stack.top is not None189 190 183-def has_app_context():191+def has_app_context() -> bool:192 """Works like :func:`has_request_context` but for the application193 context. You can also just do a boolean check on the194 :data:`current_app` object instead.195 10 unmodified lines206 but the application is not on top of the individual application207 context.208 """209 202- def __init__(self, app):210+ def __init__(self, app: "Flask") -> None:211 self.app = app212 self.url_adapter = app.create_url_adapter(None)213 self.g = app.app_ctx_globals_class()214 215 # Like request context, app contexts can be pushed multiple times216 # but there a basic "refcount" is enough to track them.217 self._refcnt = 0218 211- def push(self):219+ def push(self) -> None:220 """Binds the app context to the current context."""221 self._refcnt += 1222 _app_ctx_stack.push(self)223 appcontext_pushed.send(self.app)224 217- def pop(self, exc=_sentinel):225+ def pop(self, exc: t.Optional[BaseException] = _sentinel) -> None: # type: ignore226 """Pops the app context."""227 try:228 self._refcnt -= 1229 if self._refcnt <= 0:4 unmodified lines234 rv = _app_ctx_stack.pop()235 assert rv is self, f"Popped wrong app context. ({rv!r} instead of {self!r})"236 appcontext_popped.send(self.app)237 230- def __enter__(self):238+ def __enter__(self) -> "AppContext":239 self.push()240 return self241 234- def __exit__(self, exc_type, exc_value, tb):242+ def __exit__(243+ self, exc_type: type, exc_value: BaseException, tb: TracebackType244+ ) -> None:245 self.pop(exc_value)246 247 248 class RequestContext:25 unmodified lines274 sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in275 that situation, otherwise your unittests will leak memory.276 """277 268- def __init__(self, app, environ, request=None, session=None):278+ def __init__(279+ self,280+ app: "Flask",281+ environ: dict,282+ request: t.Optional["Request"] = None,283+ session: t.Optional["SessionMixin"] = None,284+ ) -> None:285 self.app = app286 if request is None:287 request = app.request_class(environ)288 self.request = request8 unmodified lines297 # Request contexts can be pushed multiple times and interleaved with298 # other request contexts. Now only if the last level is popped we299 # get rid of them. Additionally if an application context is missing300 # one is created implicitly so for each level we add this information285- self._implicit_app_ctx_stack = []301+ self._implicit_app_ctx_stack: t.List[t.Optional["AppContext"]] = []302 303 # indicator if the context was preserved. Next time another context304 # is pushed the preserved context is popped.305 self.preserved = False4 unmodified lines310 311 # Functions that should be executed after the request on the response312 # object. These will be called before the regular "after_request"313 # functions.298- self._after_request_functions = []314+ self._after_request_functions: t.List[AfterRequestCallable] = []315 316 @property301- def g(self):317+ def g(self) -> AppContext:318 return _app_ctx_stack.top.g319 320 @g.setter305- def g(self, value):321+ def g(self, value: AppContext) -> None:322 _app_ctx_stack.top.g = value323 308- def copy(self):324+ def copy(self) -> "RequestContext":325 """Creates a copy of this request context with the same request object.326 This can be used to move a request context to a different greenlet.327 Because the actual request object is the same this cannot be used to328 move a request context to a different thread unless access to the11 unmodified lines340 request=self.request,341 session=self.session,342 )343 328- def match_request(self):344+ def match_request(self) -> None:345 """Can be overridden by a subclass to hook into the matching346 of the request.347 """348 try:333- result = self.url_adapter.match(return_rule=True)334- self.request.url_rule, self.request.view_args = result349+ result = self.url_adapter.match(return_rule=True) # type: ignore350+ self.request.url_rule, self.request.view_args = result # type: ignore351 except HTTPException as e:352 self.request.routing_exception = e353 338- def push(self):354+ def push(self) -> None:355 """Binds the request context to the current context."""356 # If an exception occurs in debug mode or if context preservation is357 # activated under exception situations exactly one context stays358 # on the stack. The rationale is that you want to access that31 unmodified lines390 391 if self.session is None:392 self.session = session_interface.make_null_session(self.app)393 378- def pop(self, exc=_sentinel):394+ def pop(self, exc: t.Optional[BaseException] = _sentinel) -> None: # type: ignore395 """Pops the request context and unbinds it by doing that. This will396 also trigger the execution of functions registered by the397 :meth:`~flask.Flask.teardown_request` decorator.398 30 unmodified lines429 assert (430 rv is self431 ), f"Popped wrong request context. ({rv!r} instead of {self!r})"432 417- def auto_pop(self, exc):433+ def auto_pop(self, exc: t.Optional[BaseException]) -> None:434 if self.request.environ.get("flask._preserve_context") or (435 exc is not None and self.app.preserve_context_on_exception436 ):437 self.preserved = True422- self._preserved_exc = exc438+ self._preserved_exc = exc # type: ignore439 else:440 self.pop(exc)441 426- def __enter__(self):442+ def __enter__(self) -> "RequestContext":443 self.push()444 return self445 430- def __exit__(self, exc_type, exc_value, tb):446+ def __exit__(447+ self, exc_type: type, exc_value: BaseException, tb: TracebackType448+ ) -> None:449 # do not pop the request stack if we are in debug mode and an450 # exception happened. This will allow the debugger to still451 # access the request object in the interactive shell. Furthermore452 # the context can be force kept alive for the test client.453 # See flask.testing for how this works.454 self.auto_pop(exc_value)455 438- def __repr__(self):456+ def __repr__(self) -> str:457 return (458 f"<{type(self).__name__} {self.request.url!r}"459 f" [{self.request.method}] of {self.app.name}>"460 )modified:src/flask/debughelpers.py+4 added-3 removed
1 import os2+import typing as t3 from warnings import warn4 5 from .app import Flask6 from .blueprints import Blueprint85 unmodified lines92 newcls.__module__ = oldcls.__module__93 request.files.__class__ = newcls94 95 95-def _dump_loader_info(loader):96+def _dump_loader_info(loader) -> t.Generator:97 yield f"class: {type(loader).__module__}.{type(loader).__name__}"98 for key, value in sorted(loader.__dict__.items()):99 if key.startswith("_"):100 continue8 unmodified lines109 continue110 yield f"{key}: {value!r}"111 112 112-def explain_template_loading_attempts(app, template, attempts):113+def explain_template_loading_attempts(app: Flask, template, attempts) -> None:114 """This should help developers understand what failed"""115 info = [f"Locating template {template!r}:"]116 total_found = 0117 blueprint = None39 unmodified lines157 158 app.logger.info("\n".join(info))159 160 160-def explain_ignored_app_run():161+def explain_ignored_app_run() -> None:162 if os.environ.get("WERKZEUG_RUN_MAIN") != "true":163 warn(164 Warning(165 "Silently ignoring app.run() because the application is"6 unmodified linesmodified:src/flask/globals.py+10 added-4 removed
1+import typing as t2 from functools import partial3 4 from werkzeug.local import LocalProxy5 from werkzeug.local import LocalStack6 7+if t.TYPE_CHECKING:8+ from .app import Flask9+ from .ctx import AppContext10+ from .sessions import SessionMixin11+ from .wrappers import Request12 13 _request_ctx_err_msg = """\14 Working outside of request context.15 34 unmodified lines50 51 # context locals52 _request_ctx_stack = LocalStack()53 _app_ctx_stack = LocalStack()48-current_app = LocalProxy(_find_app)49-request = LocalProxy(partial(_lookup_req_object, "request"))50-session = LocalProxy(partial(_lookup_req_object, "session"))51-g = LocalProxy(partial(_lookup_app_object, "g"))54+current_app: "Flask" = LocalProxy(_find_app) # type: ignore55+request: "Request" = LocalProxy(partial(_lookup_req_object, "request")) # type: ignore56+session: "SessionMixin" = LocalProxy(partial(_lookup_req_object, "session")) # type: ignore # noqa: B95057+g: "AppContext" = LocalProxy(partial(_lookup_app_object, "g")) # type: ignoremodified:src/flask/helpers.py+45 added-29 removed
1 import os2 import socket3+import typing as t4 import warnings5+from datetime import timedelta6 from functools import update_wrapper7 from functools import wraps8 from threading import RLock9 9 unmodified lines19 from .globals import request20 from .globals import session21 from .signals import message_flashed22 23+if t.TYPE_CHECKING:24+ from .wrappers import Response25 26+22-def get_env():27+def get_env() -> str:28 """Get the environment the app is running in, indicated by the29 :envvar:`FLASK_ENV` environment variable. The default is30 ``'production'``.31 """32 return os.environ.get("FLASK_ENV") or "production"33 34 30-def get_debug_flag():35+def get_debug_flag() -> bool:36 """Get whether debug mode should be enabled for the app, indicated37 by the :envvar:`FLASK_DEBUG` environment variable. The default is38 ``True`` if :func:`.get_env` returns ``'development'``, or ``False``39 otherwise.5 unmodified lines45 46 return val.lower() not in ("0", "false", "no")47 48 44-def get_load_dotenv(default=True):49+def get_load_dotenv(default: bool = True) -> bool:50 """Get whether the user has disabled loading dotenv files by setting51 :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load the52 files.53 6 unmodified lines60 61 return val.lower() in ("0", "false", "no")62 63 59-def stream_with_context(generator_or_function):64+def stream_with_context(65+ generator_or_function: t.Union[t.Generator, t.Callable]66+) -> t.Generator:67 """Request contexts disappear when the response is started on the server.68 This is done for efficiency reasons and to make it less likely to encounter69 memory leaks with badly written WSGI middlewares. The downside is that if70 you are using streamed responses, the generator cannot access request bound26 unmodified lines97 98 .. versionadded:: 0.999 """100 try:94- gen = iter(generator_or_function)101+ gen = iter(generator_or_function) # type: ignore102 except TypeError:103 97- def decorator(*args, **kwargs):98- gen = generator_or_function(*args, **kwargs)104+ def decorator(*args: t.Any, **kwargs: t.Any) -> t.Any:105+ gen = generator_or_function(*args, **kwargs) # type: ignore106 return stream_with_context(gen)107 101- return update_wrapper(decorator, generator_or_function)108+ return update_wrapper(decorator, generator_or_function) # type: ignore109 103- def generator():110+ def generator() -> t.Generator:111 ctx = _request_ctx_stack.top112 if ctx is None:113 raise RuntimeError(114 "Attempted to stream with context but "11 unmodified lines126 try:127 yield from gen128 finally:129 if hasattr(gen, "close"):123- gen.close()130+ gen.close() # type: ignore131 132 # The trick is to start the generator. Then the code execution runs until133 # the first dummy None is yielded at which point the context was already134 # pushed. This item is discarded. Then when the iteration continues the2 unmodified lines137 next(wrapped_g)138 return wrapped_g139 140 134-def make_response(*args):141+def make_response(*args: t.Any) -> "Response":142 """Sometimes it is necessary to set additional headers in a view. Because143 views do not have to return response objects but can return a value that144 is converted into a response object by Flask itself, it becomes tricky to145 add headers to it. This function can be called instead of using a return40 unmodified lines186 args = args[0]187 return current_app.make_response(args)188 189 183-def url_for(endpoint, **values):190+def url_for(endpoint: str, **values: t.Any) -> str:191 """Generates a URL to the given endpoint with the method provided.192 193 Variable arguments that are unknown to the target endpoint are appended194 to the generated URL as query arguments. If the value of a query argument142 unmodified lines337 rv += f"#{url_quote(anchor)}"338 return rv339 340 334-def get_template_attribute(template_name, attribute):341+def get_template_attribute(template_name: str, attribute: str) -> t.Any:342 """Loads a macro (or variable) a template exports. This can be used to343 invoke a macro from within Python code. If you for example have a344 template named :file:`_cider.html` with the following contents:345 13 unmodified lines359 """360 return getattr(current_app.jinja_env.get_template(template_name).module, attribute)361 362 356-def flash(message, category="message"):363+def flash(message: str, category: str = "message") -> None:364 """Flashes a message to the next request. In order to remove the365 flashed message from the session and to display it to the user,366 the template has to call :func:`get_flashed_messages`.367 17 unmodified lines385 flashes = session.get("_flashes", [])386 flashes.append((category, message))387 session["_flashes"] = flashes388 message_flashed.send(382- current_app._get_current_object(), message=message, category=category389+ current_app._get_current_object(), # type: ignore390+ message=message,391+ category=category,392 )393 394 386-def get_flashed_messages(with_categories=False, category_filter=()):395+def get_flashed_messages(396+ with_categories: bool = False, category_filter: t.Iterable[str] = ()397+) -> t.Union[t.List[str], t.List[t.Tuple[str, str]]]:398 """Pulls all flashed messages from the session and returns them.399 Further calls in the same request to the function will return400 the same messages. By default just the messages are returned,401 but when `with_categories` is set to ``True``, the return value will216 unmodified lines618 )619 )620 621 611-def safe_join(directory, *pathnames):622+def safe_join(directory: str, *pathnames: str) -> str:623 """Safely join zero or more untrusted path components to a base624 directory to avoid escaping the base directory.625 626 :param directory: The trusted base directory.14 unmodified lines641 642 return path643 644 634-def send_from_directory(directory, path, **kwargs):645+def send_from_directory(directory: str, path: str, **kwargs: t.Any) -> "Response":646 """Send a file from within a directory using :func:`send_file`.647 648 .. code-block:: python649 21 unmodified lines671 pass some Flask-specific arguments.672 673 .. versionadded:: 0.5674 """664- return werkzeug.utils.send_from_directory(675+ return werkzeug.utils.send_from_directory( # type: ignore676 directory, path, **_prepare_send_file_kwargs(**kwargs)677 )678 679 5 unmodified lines685 .. versionchanged:: 2.0686 Inherits from Werkzeug's ``cached_property`` (and ``property``).687 """688 678- def __init__(self, fget, name=None, doc=None):689+ def __init__(690+ self,691+ fget: t.Callable[[t.Any], t.Any],692+ name: t.Optional[str] = None,693+ doc: t.Optional[str] = None,694+ ) -> None:695 super().__init__(fget, name=name, doc=doc)696 self.lock = RLock()697 682- def __get__(self, obj, type=None):698+ def __get__(self, obj: object, type: type = None) -> t.Any: # type: ignore699 if obj is None:700 return self701 702 with self.lock:703 return super().__get__(obj, type=type)704 689- def __set__(self, obj, value):705+ def __set__(self, obj: object, value: t.Any) -> None:706 with self.lock:707 super().__set__(obj, value)708 693- def __delete__(self, obj):709+ def __delete__(self, obj: object) -> None:710 with self.lock:711 super().__delete__(obj)712 713 698-def total_seconds(td):714+def total_seconds(td: timedelta) -> int:715 """Returns the total seconds from a timedelta object.716 717 :param timedelta td: the timedelta to be converted in seconds718 12 unmodified lines731 )732 return td.days * 60 * 60 * 24 + td.seconds733 734 719-def is_ip(value):735+def is_ip(value: str) -> bool:736 """Determine if the given string is an IP address.737 738 :param value: value to check739 :type value: str11 unmodified lines751 752 return False753 754 739-def run_async(func):755+def run_async(func: t.Callable[..., t.Coroutine]) -> t.Callable[..., t.Any]:756 """Return a sync function that will run the coroutine function *func*."""757 try:758 from asgiref.sync import async_to_sync759 except ImportError:7 unmodified lines767 "Async cannot be used with this combination of Python & Greenlet versions."768 )769 770 @wraps(func)755- def outer(*args, **kwargs):771+ def outer(*args: t.Any, **kwargs: t.Any) -> t.Any:772 """This function grabs the current context for the inner function.773 774 This is similar to the copy_current_xxx_context functions in the775 ctx module, except it has an async inner.3 unmodified lines779 if _request_ctx_stack.top is not None:780 ctx = _request_ctx_stack.top.copy()781 782 @wraps(func)767- async def inner(*a, **k):783+ async def inner(*a: t.Any, **k: t.Any) -> t.Any:784 """This restores the context before awaiting the func.785 786 This is required as the function must be awaited within the787 context. Only calling ``func`` (as per the7 unmodified lines795 return await func(*a, **k)796 797 return async_to_sync(inner)(*args, **kwargs)798 783- outer._flask_sync_wrapper = True799+ outer._flask_sync_wrapper = True # type: ignore800 return outermodified:src/flask/logging.py+9 added-5 removed
1 import logging2 import sys3+import typing as t4 5 from werkzeug.local import LocalProxy6 7 from .globals import request8 9+if t.TYPE_CHECKING:10+ from .app import Flask11 12+13 @LocalProxy10-def wsgi_errors_stream():14+def wsgi_errors_stream() -> t.TextIO:15 """Find the most appropriate error stream for the application. If a request16 is active, log to ``wsgi.errors``, otherwise use ``sys.stderr``.17 18 If you configure your own :class:`logging.StreamHandler`, you may want to3 unmodified lines22 """23 return request.environ["wsgi.errors"] if request else sys.stderr24 25 22-def has_level_handler(logger):26+def has_level_handler(logger: logging.Logger) -> bool:27 """Check if there is a handler in the logging chain that will handle the28 given logger's :meth:`effective level <~logging.Logger.getEffectiveLevel>`.29 """30 level = logger.getEffectiveLevel()5 unmodified lines36 37 if not current.propagate:38 break39 36- current = current.parent40+ current = current.parent # type: ignore41 42 return False43 44 45 #: Log messages to :func:`~flask.logging.wsgi_errors_stream` with the format46 #: ``[%(asctime)s] %(levelname)s in %(module)s: %(message)s``.43-default_handler = logging.StreamHandler(wsgi_errors_stream)47+default_handler = logging.StreamHandler(wsgi_errors_stream) # type: ignore48 default_handler.setFormatter(49 logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")50 )51 52 49-def create_logger(app):53+def create_logger(app: "Flask") -> logging.Logger:54 """Get the Flask app's logger and configure it if needed.55 56 The logger name will be the same as57 :attr:`app.import_name <flask.Flask.name>`.17 unmodified linesadded:src/flask/py.typed
modified:src/flask/scaffold.py+112 added-63 removed
1 import importlib.util2 import os3 import pkgutil4 import sys5+import typing as t6 from collections import defaultdict7 from functools import update_wrapper8+from json import JSONDecoder9+from json import JSONEncoder10 11 from jinja2 import FileSystemLoader12 from werkzeug.exceptions import default_exceptions13 from werkzeug.exceptions import HTTPException2 unmodified lines16 from .globals import current_app17 from .helpers import locked_cached_property18 from .helpers import send_from_directory19 from .templating import _default_template_ctx_processor20+from .typing import AfterRequestCallable21+from .typing import AppOrBlueprintKey22+from .typing import BeforeRequestCallable23+from .typing import ErrorHandlerCallable24+from .typing import TeardownCallable25+from .typing import TemplateContextProcessorCallable26+from .typing import URLDefaultCallable27+from .typing import URLValuePreprocessorCallable28 29+if t.TYPE_CHECKING:30+ from .wrappers import Response31+32 # a singleton sentinel value for parameter defaults33 _sentinel = object()34 35 22-def setupmethod(f):36+def setupmethod(f: t.Callable) -> t.Callable:37 """Wraps a method so that it performs a check in debug mode if the38 first request was already handled.39 """40 27- def wrapper_func(self, *args, **kwargs):41+ def wrapper_func(self, *args: t.Any, **kwargs: t.Any) -> t.Any:42 if self._is_setup_finished():43 raise AssertionError(44 "A setup function was called after the first request "45 "was handled. This usually indicates a bug in the"27 unmodified lines73 .. versionadded:: 2.074 """75 76 name: str63- _static_folder = None64- _static_url_path = None77+ _static_folder: t.Optional[str] = None78+ _static_url_path: t.Optional[str] = None79 80 #: JSON encoder class used by :func:`flask.json.dumps`. If a81 #: blueprint sets this, it will be used instead of the app's value.68- json_encoder = None82+ json_encoder: t.Optional[t.Type[JSONEncoder]] = None83 84 #: JSON decoder class used by :func:`flask.json.loads`. If a85 #: blueprint sets this, it will be used instead of the app's value.72- json_decoder = None86+ json_decoder: t.Optional[t.Type[JSONDecoder]] = None87 88 def __init__(89 self,76- import_name,77- static_folder=None,78- static_url_path=None,79- template_folder=None,80- root_path=None,90+ import_name: str,91+ static_folder: t.Optional[str] = None,92+ static_url_path: t.Optional[str] = None,93+ template_folder: t.Optional[str] = None,94+ root_path: t.Optional[str] = None,95 ):96 #: The name of the package or module that this object belongs97 #: to. Do not change this once it is set by the constructor.98 self.import_name = import_name24 unmodified lines123 #: To register a view function, use the :meth:`route` decorator.124 #:125 #: This data structure is internal. It should not be modified126 #: directly and its format may change at any time.113- self.view_functions = {}127+ self.view_functions: t.Dict[str, t.Callable] = {}128 129 #: A data structure of registered error handlers, in the format130 #: ``{scope: {code: {class: handler}}}```. The ``scope`` key is131 #: the name of a blueprint the handlers are active for, or6 unmodified lines138 #: decorator.139 #:140 #: This data structure is internal. It should not be modified141 #: directly and its format may change at any time.128- self.error_handler_spec = defaultdict(lambda: defaultdict(dict))142+ self.error_handler_spec: t.Dict[143+ AppOrBlueprintKey,144+ t.Dict[t.Optional[int], t.Dict[t.Type[Exception], ErrorHandlerCallable]],145+ ] = defaultdict(lambda: defaultdict(dict))146 147 #: A data structure of functions to call at the beginning of148 #: each request, in the format ``{scope: [functions]}``. The149 #: ``scope`` key is the name of a blueprint the functions are3 unmodified lines153 #: decorator.154 #:155 #: This data structure is internal. It should not be modified156 #: directly and its format may change at any time.140- self.before_request_funcs = defaultdict(list)157+ self.before_request_funcs: t.Dict[158+ AppOrBlueprintKey, t.List[BeforeRequestCallable]159+ ] = defaultdict(list)160 161 #: A data structure of functions to call at the end of each162 #: request, in the format ``{scope: [functions]}``. The163 #: ``scope`` key is the name of a blueprint the functions are3 unmodified lines167 #: decorator.168 #:169 #: This data structure is internal. It should not be modified170 #: directly and its format may change at any time.152- self.after_request_funcs = defaultdict(list)171+ self.after_request_funcs: t.Dict[172+ AppOrBlueprintKey, t.List[AfterRequestCallable]173+ ] = defaultdict(list)174 175 #: A data structure of functions to call at the end of each176 #: request even if an exception is raised, in the format177 #: ``{scope: [functions]}``. The ``scope`` key is the name of a4 unmodified lines182 #: decorator.183 #:184 #: This data structure is internal. It should not be modified185 #: directly and its format may change at any time.165- self.teardown_request_funcs = defaultdict(list)186+ self.teardown_request_funcs: t.Dict[187+ AppOrBlueprintKey, t.List[TeardownCallable]188+ ] = defaultdict(list)189 190 #: A data structure of functions to call to pass extra context191 #: values when rendering templates, in the format192 #: ``{scope: [functions]}``. The ``scope`` key is the name of a4 unmodified lines197 #: decorator.198 #:199 #: This data structure is internal. It should not be modified200 #: directly and its format may change at any time.178- self.template_context_processors = defaultdict(179- list, {None: [_default_template_ctx_processor]}180- )201+ self.template_context_processors: t.Dict[202+ AppOrBlueprintKey, t.List[TemplateContextProcessorCallable]203+ ] = defaultdict(list, {None: [_default_template_ctx_processor]})204 205 #: A data structure of functions to call to modify the keyword206 #: arguments passed to the view function, in the format207 #: ``{scope: [functions]}``. The ``scope`` key is the name of a4 unmodified lines212 #: :meth:`url_value_preprocessor` decorator.213 #:214 #: This data structure is internal. It should not be modified215 #: directly and its format may change at any time.193- self.url_value_preprocessors = defaultdict(list)216+ self.url_value_preprocessors: t.Dict[217+ AppOrBlueprintKey,218+ t.List[URLValuePreprocessorCallable],219+ ] = defaultdict(list)220 221 #: A data structure of functions to call to modify the keyword222 #: arguments when generating URLs, in the format223 #: ``{scope: [functions]}``. The ``scope`` key is the name of a4 unmodified lines228 #: decorator.229 #:230 #: This data structure is internal. It should not be modified231 #: directly and its format may change at any time.206- self.url_default_functions = defaultdict(list)232+ self.url_default_functions: t.Dict[233+ AppOrBlueprintKey, t.List[URLDefaultCallable]234+ ] = defaultdict(list)235 208- def __repr__(self):236+ def __repr__(self) -> str:237 return f"<{type(self).__name__} {self.name!r}>"238 211- def _is_setup_finished(self):239+ def _is_setup_finished(self) -> bool:240 raise NotImplementedError241 242 @property215- def static_folder(self):243+ def static_folder(self) -> t.Optional[str]:244 """The absolute path to the configured static folder. ``None``245 if no static folder is set.246 """247 if self._static_folder is not None:248 return os.path.join(self.root_path, self._static_folder)249+ else:250+ return None251 252 @static_folder.setter223- def static_folder(self, value):253+ def static_folder(self, value: t.Optional[str]) -> None:254 if value is not None:255 value = os.fspath(value).rstrip(r"\/")256 257 self._static_folder = value258 259 @property230- def has_static_folder(self):260+ def has_static_folder(self) -> bool:261 """``True`` if :attr:`static_folder` is set.262 263 .. versionadded:: 0.5264 """265 return self.static_folder is not None266 267 @property238- def static_url_path(self):268+ def static_url_path(self) -> t.Optional[str]:269 """The URL prefix that the static route will be accessible from.270 271 If it was not configured during init, it is derived from272 :attr:`static_folder`.4 unmodified lines277 if self.static_folder is not None:278 basename = os.path.basename(self.static_folder)279 return f"/{basename}".rstrip("/")280 281+ return None282+283 @static_url_path.setter252- def static_url_path(self, value):284+ def static_url_path(self, value: t.Optional[str]) -> None:285 if value is not None:286 value = value.rstrip("/")287 288 self._static_url_path = value289 258- def get_send_file_max_age(self, filename):290+ def get_send_file_max_age(self, filename: str) -> t.Optional[int]:291 """Used by :func:`send_file` to determine the ``max_age`` cache292 value for a given file path if it wasn't passed.293 294 By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from12 unmodified lines307 return None308 309 return int(value.total_seconds())310 279- def send_static_file(self, filename):311+ def send_static_file(self, filename: str) -> "Response":312 """The view function used to serve files from313 :attr:`static_folder`. A route is automatically registered for314 this view at :attr:`static_url_path` if :attr:`static_folder` is315 set.5 unmodified lines321 322 # send_file only knows to call get_send_file_max_age on the app,323 # call it here so it works for blueprints too.324 max_age = self.get_send_file_max_age(filename)293- return send_from_directory(self.static_folder, filename, max_age=max_age)325+ return send_from_directory(326+ t.cast(str, self.static_folder), filename, max_age=max_age327+ )328 329 @locked_cached_property296- def jinja_loader(self):330+ def jinja_loader(self) -> t.Optional[FileSystemLoader]:331 """The Jinja loader for this object's templates. By default this332 is a class :class:`jinja2.loaders.FileSystemLoader` to333 :attr:`template_folder` if it is set.334 335 .. versionadded:: 0.5336 """337 if self.template_folder is not None:338 return FileSystemLoader(os.path.join(self.root_path, self.template_folder))339+ else:340+ return None341 306- def open_resource(self, resource, mode="rb"):342+ def open_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:343 """Open a resource file relative to :attr:`root_path` for344 reading.345 346 For example, if the file ``schema.sql`` is next to the file14 unmodified lines361 raise ValueError("Resources can only be opened for reading.")362 363 return open(os.path.join(self.root_path, resource), mode)364 329- def _method_route(self, method, rule, options):365+ def _method_route(self, method: str, rule: str, options: dict) -> t.Callable:366 if "methods" in options:367 raise TypeError("Use the 'route' decorator to use the 'methods' argument.")368 369 return self.route(rule, methods=[method], **options)370 335- def get(self, rule, **options):371+ def get(self, rule: str, **options: t.Any) -> t.Callable:372 """Shortcut for :meth:`route` with ``methods=["GET"]``.373 374 .. versionadded:: 2.0375 """376 return self._method_route("GET", rule, options)377 342- def post(self, rule, **options):378+ def post(self, rule: str, **options: t.Any) -> t.Callable:379 """Shortcut for :meth:`route` with ``methods=["POST"]``.380 381 .. versionadded:: 2.0382 """383 return self._method_route("POST", rule, options)384 349- def put(self, rule, **options):385+ def put(self, rule: str, **options: t.Any) -> t.Callable:386 """Shortcut for :meth:`route` with ``methods=["PUT"]``.387 388 .. versionadded:: 2.0389 """390 return self._method_route("PUT", rule, options)391 356- def delete(self, rule, **options):392+ def delete(self, rule: str, **options: t.Any) -> t.Callable:393 """Shortcut for :meth:`route` with ``methods=["DELETE"]``.394 395 .. versionadded:: 2.0396 """397 return self._method_route("DELETE", rule, options)398 363- def patch(self, rule, **options):399+ def patch(self, rule: str, **options: t.Any) -> t.Callable:400 """Shortcut for :meth:`route` with ``methods=["PATCH"]``.401 402 .. versionadded:: 2.0403 """404 return self._method_route("PATCH", rule, options)405 370- def route(self, rule, **options):406+ def route(self, rule: str, **options: t.Any) -> t.Callable:407 """Decorate a view function to register it with the given URL408 rule and options. Calls :meth:`add_url_rule`, which has more409 details about the implementation.410 15 unmodified lines426 :param options: Extra options passed to the427 :class:`~werkzeug.routing.Rule` object.428 """429 394- def decorator(f):430+ def decorator(f: t.Callable) -> t.Callable:431 endpoint = options.pop("endpoint", None)432 self.add_url_rule(rule, endpoint, f, **options)433 return f434 1 unmodified line436 437 @setupmethod438 def add_url_rule(439 self,404- rule,405- endpoint=None,406- view_func=None,407- provide_automatic_options=None,408- **options,409- ):440+ rule: str,441+ endpoint: t.Optional[str] = None,442+ view_func: t.Optional[t.Callable] = None,443+ provide_automatic_options: t.Optional[bool] = None,444+ **options: t.Any,445+ ) -> t.Callable:446 """Register a rule for routing incoming requests and building447 URLs. The :meth:`route` decorator is a shortcut to call this448 with the ``view_func`` argument. These are equivalent:449 51 unmodified lines501 :class:`~werkzeug.routing.Rule` object.502 """503 raise NotImplementedError504 469- def endpoint(self, endpoint):505+ def endpoint(self, endpoint: str) -> t.Callable:506 """Decorate a view function to register it for the given507 endpoint. Used if a rule is added without a ``view_func`` with508 :meth:`add_url_rule`.509 15 unmodified lines525 526 return decorator527 528 @setupmethod493- def before_request(self, f):529+ def before_request(self, f: BeforeRequestCallable) -> BeforeRequestCallable:530 """Register a function to run before each request.531 532 For example, this can be used to open a database connection, or533 to load the logged in user from the session.13 unmodified lines547 self.before_request_funcs.setdefault(None, []).append(self.ensure_sync(f))548 return f549 550 @setupmethod515- def after_request(self, f):551+ def after_request(self, f: AfterRequestCallable) -> AfterRequestCallable:552 """Register a function to run after each request to this object.553 554 The function is called with the response object, and must return555 a response object. This allows the functions to modify or7 unmodified lines563 self.after_request_funcs.setdefault(None, []).append(self.ensure_sync(f))564 return f565 566 @setupmethod531- def teardown_request(self, f):567+ def teardown_request(self, f: TeardownCallable) -> TeardownCallable:568 """Register a function to be run at the end of each request,569 regardless of whether there was an exception or not. These functions570 are executed when the request context is popped, even if not an571 actual request was performed.30 unmodified lines602 self.teardown_request_funcs.setdefault(None, []).append(self.ensure_sync(f))603 return f604 605 @setupmethod570- def context_processor(self, f):606+ def context_processor(607+ self, f: TemplateContextProcessorCallable608+ ) -> TemplateContextProcessorCallable:609 """Registers a template context processor function."""610 self.template_context_processors[None].append(f)611 return f612 613 @setupmethod576- def url_value_preprocessor(self, f):614+ def url_value_preprocessor(615+ self, f: URLValuePreprocessorCallable616+ ) -> URLValuePreprocessorCallable:617 """Register a URL value preprocessor function for all view618 functions in the application. These functions will be called before the619 :meth:`before_request` functions.620 8 unmodified lines629 self.url_value_preprocessors[None].append(f)630 return f631 632 @setupmethod593- def url_defaults(self, f):633+ def url_defaults(self, f: URLDefaultCallable) -> URLDefaultCallable:634 """Callback function for URL defaults for all view functions of the635 application. It's called with the endpoint and values and should636 update the values passed in place.637 """638 self.url_default_functions[None].append(f)639 return f640 641 @setupmethod602- def errorhandler(self, code_or_exception):642+ def errorhandler(643+ self, code_or_exception: t.Union[t.Type[Exception], int]644+ ) -> t.Callable:645 """Register a function to handle errors by code or exception class.646 647 A decorator that is used to register a function given an648 error code. Example::21 unmodified lines670 :param code_or_exception: the code as integer for the handler, or671 an arbitrary exception672 """673 632- def decorator(f):674+ def decorator(f: ErrorHandlerCallable) -> ErrorHandlerCallable:675 self.register_error_handler(code_or_exception, f)676 return f677 678 return decorator679 680 @setupmethod639- def register_error_handler(self, code_or_exception, f):681+ def register_error_handler(682+ self,683+ code_or_exception: t.Union[t.Type[Exception], int],684+ f: ErrorHandlerCallable,685+ ) -> None:686 """Alternative error attach function to the :meth:`errorhandler`687 decorator that is more straightforward to use for non decorator688 usage.689 17 unmodified lines707 708 self.error_handler_spec[None][code][exc_class] = self.ensure_sync(f)709 710 @staticmethod665- def _get_exc_class_and_code(exc_class_or_code):711+ def _get_exc_class_and_code(712+ exc_class_or_code: t.Union[t.Type[Exception], int]713+ ) -> t.Tuple[t.Type[Exception], t.Optional[int]]:714 """Get the exception class being handled. For HTTP status codes715 or ``HTTPException`` subclasses, return both the exception and716 status code.717 718 :param exc_class_or_code: Any exception class, or an HTTP status719 code as an integer.720 """721+ exc_class: t.Type[Exception]722 if isinstance(exc_class_or_code, int):723 exc_class = default_exceptions[exc_class_or_code]724 else:725 exc_class = exc_class_or_code6 unmodified lines732 return exc_class, exc_class.code733 else:734 return exc_class, None735 687- def ensure_sync(self, func):736+ def ensure_sync(self, func: t.Callable) -> t.Callable:737 raise NotImplementedError()738 739 691-def _endpoint_from_view_func(view_func):740+def _endpoint_from_view_func(view_func: t.Callable) -> str:741 """Internal helper that returns the default endpoint for a given742 function. This always is the function name.743 """744 assert view_func is not None, "expected view func if endpoint is not provided."745 return view_func.__name__746 747 699-def get_root_path(import_name):748+def get_root_path(import_name: str) -> str:749 """Find the root path of a package, or the path that contains a750 module. If it cannot be found, returns the current working751 directory.752 16 unmodified lines769 if loader is None or import_name == "__main__":770 return os.getcwd()771 772 if hasattr(loader, "get_filename"):724- filepath = loader.get_filename(import_name)773+ filepath = loader.get_filename(import_name) # type: ignore774 else:775 # Fall back to imports.776 __import__(import_name)777 mod = sys.modules[import_name]92 unmodified lines870 871 return package_path872 873 825-def find_package(import_name):874+def find_package(import_name: str):875 """Find the prefix that a package is installed under, and the path876 that it would be imported from.877 878 The prefix is the directory containing the standard directory35 unmodified linesmodified:src/flask/sessions.py+44 added-26 removed
1 import hashlib2+import typing as t3 import warnings4 from collections.abc import MutableMapping5 from datetime import datetime6 3 unmodified lines10 11 from .helpers import is_ip12 from .json.tag import TaggedJSONSerializer13 14+if t.TYPE_CHECKING:15+ from .app import Flask16+ from .wrappers import Request, Response17 18+19 class SessionMixin(MutableMapping):20 """Expands a basic dictionary with session attributes."""21 22 @property18- def permanent(self):23+ def permanent(self) -> bool:24 """This reflects the ``'_permanent'`` key in the dict."""25 return self.get("_permanent", False)26 27 @permanent.setter23- def permanent(self, value):28+ def permanent(self, value: bool) -> None:29 self["_permanent"] = bool(value)30 31 #: Some implementations can detect whether a session is newly32 #: created, but that is not guaranteed. Use with caution. The mixin32 unmodified lines65 #: header, which allows caching proxies to cache different pages for66 #: different users.67 accessed = False68 64- def __init__(self, initial=None):65- def on_update(self):69+ def __init__(self, initial: t.Any = None) -> None:70+ def on_update(self) -> None:71 self.modified = True72 self.accessed = True73 74 super().__init__(initial, on_update)75 71- def __getitem__(self, key):76+ def __getitem__(self, key: str) -> t.Any:77 self.accessed = True78 return super().__getitem__(key)79 75- def get(self, key, default=None):80+ def get(self, key: str, default: t.Any = None) -> t.Any:81 self.accessed = True82 return super().get(key, default)83 79- def setdefault(self, key, default=None):84+ def setdefault(self, key: str, default: t.Any = None) -> t.Any:85 self.accessed = True86 return super().setdefault(key, default)87 88 2 unmodified lines91 available. Will still allow read-only access to the empty session92 but fail on setting.93 """94 90- def _fail(self, *args, **kwargs):95+ def _fail(self, *args: t.Any, **kwargs: t.Any) -> t.NoReturn:96 raise RuntimeError(97 "The session is unavailable because no secret "98 "key was set. Set the secret_key on the "99 "application to something unique and secret."100 )101 97- __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail102+ __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail # type: ignore # noqa: B950103 del _fail104 105 106 class SessionInterface:38 unmodified lines145 #:146 #: .. versionadded:: 0.10147 pickle_based = False148 144- def make_null_session(self, app):149+ def make_null_session(self, app: "Flask") -> NullSession:150 """Creates a null session which acts as a replacement object if the151 real session support could not be loaded due to a configuration152 error. This mainly aids the user experience because the job of the153 null session is to still support lookup without complaining but3 unmodified lines157 This creates an instance of :attr:`null_session_class` by default.158 """159 return self.null_session_class()160 156- def is_null_session(self, obj):161+ def is_null_session(self, obj: object) -> bool:162 """Checks if a given object is a null session. Null sessions are163 not asked to be saved.164 165 This checks if the object is an instance of :attr:`null_session_class`166 by default.167 """168 return isinstance(obj, self.null_session_class)169 165- def get_cookie_name(self, app):170+ def get_cookie_name(self, app: "Flask") -> str:171 """Returns the name of the session cookie.172 173 Uses ``app.session_cookie_name`` which is set to ``SESSION_COOKIE_NAME``174 """175 return app.session_cookie_name176 172- def get_cookie_domain(self, app):177+ def get_cookie_domain(self, app: "Flask") -> t.Optional[str]:178 """Returns the domain that should be set for the session cookie.179 180 Uses ``SESSION_COOKIE_DOMAIN`` if it is configured, otherwise181 falls back to detecting the domain based on ``SERVER_NAME``.49 unmodified lines231 232 app.config["SESSION_COOKIE_DOMAIN"] = rv233 return rv234 230- def get_cookie_path(self, app):235+ def get_cookie_path(self, app: "Flask") -> str:236 """Returns the path for which the cookie should be valid. The237 default implementation uses the value from the ``SESSION_COOKIE_PATH``238 config var if it's set, and falls back to ``APPLICATION_ROOT`` or239 uses ``/`` if it's ``None``.240 """241 return app.config["SESSION_COOKIE_PATH"] or app.config["APPLICATION_ROOT"]242 238- def get_cookie_httponly(self, app):243+ def get_cookie_httponly(self, app: "Flask") -> bool:244 """Returns True if the session cookie should be httponly. This245 currently just returns the value of the ``SESSION_COOKIE_HTTPONLY``246 config var.247 """248 return app.config["SESSION_COOKIE_HTTPONLY"]249 245- def get_cookie_secure(self, app):250+ def get_cookie_secure(self, app: "Flask") -> bool:251 """Returns True if the cookie should be secure. This currently252 just returns the value of the ``SESSION_COOKIE_SECURE`` setting.253 """254 return app.config["SESSION_COOKIE_SECURE"]255 251- def get_cookie_samesite(self, app):256+ def get_cookie_samesite(self, app: "Flask") -> str:257 """Return ``'Strict'`` or ``'Lax'`` if the cookie should use the258 ``SameSite`` attribute. This currently just returns the value of259 the :data:`SESSION_COOKIE_SAMESITE` setting.260 """261 return app.config["SESSION_COOKIE_SAMESITE"]262 258- def get_expiration_time(self, app, session):263+ def get_expiration_time(264+ self, app: "Flask", session: SessionMixin265+ ) -> t.Optional[datetime]:266 """A helper method that returns an expiration date for the session267 or ``None`` if the session is linked to the browser session. The268 default implementation returns now + the permanent session269 lifetime configured on the application.270 """271 if session.permanent:272 return datetime.utcnow() + app.permanent_session_lifetime273+ return None274 267- def should_set_cookie(self, app, session):275+ def should_set_cookie(self, app: "Flask", session: SessionMixin) -> bool:276 """Used by session backends to determine if a ``Set-Cookie`` header277 should be set for this session cookie for this response. If the session278 has been modified, the cookie is set. If the session is permanent and279 the ``SESSION_REFRESH_EACH_REQUEST`` config is true, the cookie is7 unmodified lines287 return session.modified or (288 session.permanent and app.config["SESSION_REFRESH_EACH_REQUEST"]289 )290 283- def open_session(self, app, request):291+ def open_session(292+ self, app: "Flask", request: "Request"293+ ) -> t.Optional[SessionMixin]:294 """This method has to be implemented and must either return ``None``295 in case the loading failed because of a configuration error or an296 instance of a session object which implements a dictionary like297 interface + the methods and attributes on :class:`SessionMixin`.298 """299 raise NotImplementedError()300 291- def save_session(self, app, session, response):301+ def save_session(302+ self, app: "Flask", session: SessionMixin, response: "Response"303+ ) -> None:304 """This is called for actual sessions returned by :meth:`open_session`305 at the end of the request. This is still called during a request306 context so if you absolutely need access to the request you can do307 that.22 unmodified lines330 #: such as datetime objects or tuples.331 serializer = session_json_serializer332 session_class = SecureCookieSession333 322- def get_signing_serializer(self, app):334+ def get_signing_serializer(335+ self, app: "Flask"336+ ) -> t.Optional[URLSafeTimedSerializer]:337 if not app.secret_key:338 return None339 signer_kwargs = dict(340 key_derivation=self.key_derivation, digest_method=self.digest_method4 unmodified lines345 serializer=self.serializer,346 signer_kwargs=signer_kwargs,347 )348 335- def open_session(self, app, request):349+ def open_session(350+ self, app: "Flask", request: "Request"351+ ) -> t.Optional[SecureCookieSession]:352 s = self.get_signing_serializer(app)353 if s is None:354 return None355 val = request.cookies.get(self.get_cookie_name(app))5 unmodified lines361 return self.session_class(data)362 except BadSignature:363 return self.session_class()364 349- def save_session(self, app, session, response):365+ def save_session(366+ self, app: "Flask", session: SessionMixin, response: "Response"367+ ) -> None:368 name = self.get_cookie_name(app)369 domain = self.get_cookie_domain(app)370 path = self.get_cookie_path(app)371 secure = self.get_cookie_secure(app)17 unmodified lines389 return390 391 httponly = self.get_cookie_httponly(app)392 expires = self.get_expiration_time(app, session)375- val = self.get_signing_serializer(app).dumps(dict(session))393+ val = self.get_signing_serializer(app).dumps(dict(session)) # type: ignore394 response.set_cookie(395 name,378- val,396+ val, # type: ignore397 expires=expires,398 httponly=httponly,399 domain=domain,400 path=path,3 unmodified linesmodified:src/flask/signals.py+7 added-5 removed
1+import typing as t2+3 try:4 from blinker import Namespace5 6 signals_available = True7 except ImportError:8 signals_available = False9 8- class Namespace:9- def signal(self, name, doc=None):10+ class Namespace: # type: ignore11+ def signal(self, name: str, doc: t.Optional[str] = None) -> "_FakeSignal":12 return _FakeSignal(name, doc)13 14 class _FakeSignal:15 """If blinker is unavailable, create a fake class with the same1 unmodified line17 error on anything else. Instead of doing anything on send, it18 will just ignore the arguments and do nothing instead.19 """20 19- def __init__(self, name, doc=None):21+ def __init__(self, name: str, doc: t.Optional[str] = None) -> None:22 self.name = name23 self.__doc__ = doc24 23- def send(self, *args, **kwargs):25+ def send(self, *args: t.Any, **kwargs: t.Any) -> t.Any:26 pass27 26- def _fail(self, *args, **kwargs):28+ def _fail(self, *args: t.Any, **kwargs: t.Any) -> t.Any:29 raise RuntimeError(30 "Signalling support is unavailable because the blinker"31 " library is not installed."32 )24 unmodified linesmodified:src/flask/templating.py+28 added-11 removed
1+import typing as t2+3 from jinja2 import BaseLoader4 from jinja2 import Environment as BaseEnvironment5+from jinja2 import Template6 from jinja2 import TemplateNotFound7 8 from .globals import _app_ctx_stack9 from .globals import _request_ctx_stack10 from .signals import before_render_template11 from .signals import template_rendered12 13+if t.TYPE_CHECKING:14+ from .app import Flask15+ from .scaffold import Scaffold16 17+11-def _default_template_ctx_processor():18+def _default_template_ctx_processor() -> t.Dict[str, t.Any]:19 """Default template context processor. Injects `request`,20 `session` and `g`.21 """22 reqctx = _request_ctx_stack.top12 unmodified lines35 knowledge of how Flask's blueprint works so that it can prepend the36 name of the blueprint to referenced templates if necessary.37 """38 32- def __init__(self, app, **options):39+ def __init__(self, app: "Flask", **options: t.Any) -> None:40 if "loader" not in options:41 options["loader"] = app.create_global_jinja_loader()42 BaseEnvironment.__init__(self, **options)43 self.app = app3 unmodified lines47 """A loader that looks for templates in the application and all48 the blueprint folders.49 """50 44- def __init__(self, app):51+ def __init__(self, app: "Flask") -> None:52 self.app = app53 47- def get_source(self, environment, template):54+ def get_source(55+ self, environment: Environment, template: str56+ ) -> t.Tuple[str, t.Optional[str], t.Callable]:57 if self.app.config["EXPLAIN_TEMPLATE_LOADING"]:58 return self._get_source_explained(environment, template)59 return self._get_source_fast(environment, template)60 52- def _get_source_explained(self, environment, template):61+ def _get_source_explained(62+ self, environment: Environment, template: str63+ ) -> t.Tuple[str, t.Optional[str], t.Callable]:64 attempts = []65 trv = None66 67 for srcobj, loader in self._iter_loaders(template):12 unmodified lines80 if trv is not None:81 return trv82 raise TemplateNotFound(template)83 73- def _get_source_fast(self, environment, template):84+ def _get_source_fast(85+ self, environment: Environment, template: str86+ ) -> t.Tuple[str, t.Optional[str], t.Callable]:87 for _srcobj, loader in self._iter_loaders(template):88 try:89 return loader.get_source(environment, template)90 except TemplateNotFound:91 continue92 raise TemplateNotFound(template)93 81- def _iter_loaders(self, template):94+ def _iter_loaders(95+ self, template: str96+ ) -> t.Generator[t.Tuple["Scaffold", BaseLoader], None, None]:97 loader = self.app.jinja_loader98 if loader is not None:99 yield self.app, loader100 1 unmodified line102 loader = blueprint.jinja_loader103 if loader is not None:104 yield blueprint, loader105 91- def list_templates(self):106+ def list_templates(self) -> t.List[str]:107 result = set()108 loader = self.app.jinja_loader109 if loader is not None:110 result.update(loader.list_templates())6 unmodified lines117 118 return list(result)119 120 106-def _render(template, context, app):121+def _render(template: Template, context: dict, app: "Flask") -> str:122 """Renders the template and fires the signal"""123 124 before_render_template.send(app, template=template, context=context)125 rv = template.render(context)126 template_rendered.send(app, template=template, context=context)127 return rv128 129 115-def render_template(template_name_or_list, **context):130+def render_template(131+ template_name_or_list: t.Union[str, t.List[str]], **context: t.Any132+) -> str:133 """Renders a template from the template folder with the given134 context.135 136 :param template_name_or_list: the name of the template to be10 unmodified lines147 ctx.app,148 )149 150 134-def render_template_string(source, **context):151+def render_template_string(source: str, **context: t.Any) -> str:152 """Renders a template from the given template source string153 with the given context. Template variables will be autoescaped.154 155 :param source: the source code of the template to be7 unmodified linesmodified:src/flask/testing.py+38 added-19 removed
1+import typing as t2 from contextlib import contextmanager3 from copy import copy4+from types import TracebackType5 6 import werkzeug.test7 from click.testing import CliRunner8 from werkzeug.test import Client2 unmodified lines11 12 from . import _request_ctx_stack13 from .cli import ScriptInfo14 from .json import dumps as json_dumps15+from .sessions import SessionMixin16 17+if t.TYPE_CHECKING:18+ from .app import Flask19+ from .wrappers import Response20 21+22 class EnvironBuilder(werkzeug.test.EnvironBuilder):23 """An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the24 application.25 16 unmodified lines42 """43 44 def __init__(45 self,39- app,40- path="/",41- base_url=None,42- subdomain=None,43- url_scheme=None,44- *args,45- **kwargs,46- ):46+ app: "Flask",47+ path: str = "/",48+ base_url: t.Optional[str] = None,49+ subdomain: t.Optional[str] = None,50+ url_scheme: t.Optional[str] = None,51+ *args: t.Any,52+ **kwargs: t.Any,53+ ) -> None:54 assert not (base_url or subdomain or url_scheme) or (55 base_url is not None56 ) != bool(57 subdomain or url_scheme22 unmodified lines80 81 self.app = app82 super().__init__(path, base_url, *args, **kwargs)83 77- def json_dumps(self, obj, **kwargs):84+ def json_dumps(self, obj: t.Any, **kwargs: t.Any) -> str: # type: ignore85 """Serialize ``obj`` to a JSON-formatted string.86 87 The serialization will be configured according to the config associated88 with this EnvironBuilder's ``app``.16 unmodified lines105 106 Basic usage is outlined in the :doc:`/testing` chapter.107 """108 109+ application: "Flask"110 preserve_context = False111 104- def __init__(self, *args, **kwargs):112+ def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:113 super().__init__(*args, **kwargs)114 self.environ_base = {115 "REMOTE_ADDR": "127.0.0.1",116 "HTTP_USER_AGENT": f"werkzeug/{werkzeug.__version__}",117 }118 119 @contextmanager112- def session_transaction(self, *args, **kwargs):120+ def session_transaction(121+ self, *args: t.Any, **kwargs: t.Any122+ ) -> t.Generator[SessionMixin, None, None]:123 """When used in combination with a ``with`` statement this opens a124 session transaction. This can be used to modify the session that125 the test client uses. Once the ``with`` block is left the session is126 stored back.43 unmodified lines170 session_interface.save_session(app, sess, resp)171 headers = resp.get_wsgi_headers(c.request.environ)172 self.cookie_jar.extract_wsgi(c.request.environ, headers)173 164- def open(165- self, *args, as_tuple=False, buffered=False, follow_redirects=False, **kwargs166- ):174+ def open( # type: ignore175+ self,176+ *args: t.Any,177+ as_tuple: bool = False,178+ buffered: bool = False,179+ follow_redirects: bool = False,180+ **kwargs: t.Any,181+ ) -> "Response":182 # Same logic as super.open, but apply environ_base and preserve_context.183 request = None184 185 def copy_environ(other):26 unmodified lines212 request = builder.get_request()213 finally:214 builder.close()215 201- return super().open(216+ return super().open( # type: ignore217 request,218 as_tuple=as_tuple,219 buffered=buffered,220 follow_redirects=follow_redirects,221 )222 208- def __enter__(self):223+ def __enter__(self) -> "FlaskClient":224 if self.preserve_context:225 raise RuntimeError("Cannot nest client invocations")226 self.preserve_context = True227 return self228 214- def __exit__(self, exc_type, exc_value, tb):229+ def __exit__(230+ self, exc_type: type, exc_value: BaseException, tb: TracebackType231+ ) -> None:232 self.preserve_context = False233 234 # Normally the request context is preserved until the next235 # request in the same thread comes. When the client exits we13 unmodified lines249 CLI commands. Typically created using250 :meth:`~flask.Flask.test_cli_runner`. See :ref:`testing-cli`.251 """252 236- def __init__(self, app, **kwargs):253+ def __init__(self, app: "Flask", **kwargs: t.Any) -> None:254 self.app = app255 super().__init__(**kwargs)256 240- def invoke(self, cli=None, args=None, **kwargs):257+ def invoke( # type: ignore258+ self, cli: t.Any = None, args: t.Any = None, **kwargs: t.Any259+ ) -> t.Any:260 """Invokes a CLI command in an isolated environment. See261 :meth:`CliRunner.invoke <click.testing.CliRunner.invoke>` for262 full method documentation. See :ref:`testing-cli` for examples.263 17 unmodified linesadded:src/flask/typing.py+46 added
1+import typing as t2+3+4+if t.TYPE_CHECKING:5+ from werkzeug.datastructures import Headers # noqa: F4016+ from wsgiref.types import WSGIApplication # noqa: F4017+ from .wrappers import Response # noqa: F4018+9+# The possible types that are directly convertible or are a Response object.10+ResponseValue = t.Union[11+ "Response",12+ t.AnyStr,13+ t.Dict[str, t.Any], # any jsonify-able dict14+ t.Generator[t.AnyStr, None, None],15+]16+StatusCode = int17+18+# the possible types for an individual HTTP header19+HeaderName = str20+HeaderValue = t.Union[str, t.List[str], t.Tuple[str, ...]]21+22+# the possible types for HTTP headers23+HeadersValue = t.Union[24+ "Headers", t.Dict[HeaderName, HeaderValue], t.List[t.Tuple[HeaderName, HeaderValue]]25+]26+27+# The possible types returned by a route function.28+ResponseReturnValue = t.Union[29+ ResponseValue,30+ t.Tuple[ResponseValue, HeadersValue],31+ t.Tuple[ResponseValue, StatusCode],32+ t.Tuple[ResponseValue, StatusCode, HeadersValue],33+ "WSGIApplication",34+]35+36+AppOrBlueprintKey = t.Optional[str] # The App key is None, whereas blueprints are named37+AfterRequestCallable = t.Callable[["Response"], "Response"]38+BeforeRequestCallable = t.Callable[[], None]39+ErrorHandlerCallable = t.Callable[[Exception], ResponseReturnValue]40+TeardownCallable = t.Callable[[t.Optional[BaseException]], "Response"]41+TemplateContextProcessorCallable = t.Callable[[], t.Dict[str, t.Any]]42+TemplateFilterCallable = t.Callable[[t.Any], str]43+TemplateGlobalCallable = t.Callable[[], t.Any]44+TemplateTestCallable = t.Callable[[t.Any], bool]45+URLDefaultCallable = t.Callable[[str, dict], None]46+URLValuePreprocessorCallable = t.Callable[[t.Optional[str], t.Optional[dict]], None]modified:src/flask/views.py+16 added-11 removed
1+import typing as t2+3 from .globals import request4+from .typing import ResponseReturnValue5 6 7 http_method_funcs = frozenset(8 ["get", "post", "head", "options", "delete", "put", "trace", "patch"]32 unmodified lines41 generated view function!42 """43 44 #: A list of methods this view can handle.42- methods = None45+ methods: t.Optional[t.List[str]] = None46 47 #: Setting this disables or force-enables the automatic options handling.45- provide_automatic_options = None48+ provide_automatic_options: t.Optional[bool] = None49 50 #: The canonical way to decorate class-based views is to decorate the51 #: return value of as_view(). However since this moves parts of the52 #: logic from the class declaration to the place where it's hooked2 unmodified lines55 #: You can place one or more decorators in this list and whenever the56 #: view function is created the result is automatically decorated.57 #:58 #: .. versionadded:: 0.856- decorators = ()59+ decorators: t.List[t.Callable] = []60 58- def dispatch_request(self):61+ def dispatch_request(self) -> ResponseReturnValue:62 """Subclasses have to override this method to implement the63 actual view function code. This method is called with all64 the arguments from the URL rule.65 """66 raise NotImplementedError()67 68 @classmethod66- def as_view(cls, name, *class_args, **class_kwargs):69+ def as_view(70+ cls, name: str, *class_args: t.Any, **class_kwargs: t.Any71+ ) -> t.Callable:72 """Converts the class into an actual view function that can be used73 with the routing system. Internally this generates a function on the74 fly which will instantiate the :class:`View` on each request and call75 the :meth:`dispatch_request` method on it.1 unmodified line77 The arguments passed to :meth:`as_view` are forwarded to the78 constructor of the class.79 """80 76- def view(*args, **kwargs):77- self = view.view_class(*class_args, **class_kwargs)81+ def view(*args: t.Any, **kwargs: t.Any) -> ResponseReturnValue:82+ self = view.view_class(*class_args, **class_kwargs) # type: ignore83 return self.dispatch_request(*args, **kwargs)84 85 if cls.decorators:86 view.__name__ = name5 unmodified lines92 # first of all it allows us to easily figure out what class-based93 # view this thing came from, secondly it's also used for instantiating94 # the view class so you can actually replace it with something else95 # for testing purposes and debugging.91- view.view_class = cls96+ view.view_class = cls # type: ignore97 view.__name__ = name98 view.__doc__ = cls.__doc__99 view.__module__ = cls.__module__95- view.methods = cls.methods96- view.provide_automatic_options = cls.provide_automatic_options100+ view.methods = cls.methods # type: ignore101+ view.provide_automatic_options = cls.provide_automatic_options # type: ignore102 return view103 104 105 class MethodViewType(type):38 unmodified lines144 145 app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))146 """147 143- def dispatch_request(self, *args, **kwargs):148+ def dispatch_request(self, *args: t.Any, **kwargs: t.Any) -> ResponseReturnValue:149 meth = getattr(self, request.method.lower(), None)150 151 # If the request method is HEAD and we don't have a handler for it152 # retry with GET.5 unmodified linesmodified:src/flask/wrappers.py+20 added-9 removed
1+import typing as t2+3 from werkzeug.exceptions import BadRequest4 from werkzeug.wrappers import Request as RequestBase5 from werkzeug.wrappers import Response as ResponseBase6 7 from . import json8 from .globals import current_app9 10+if t.TYPE_CHECKING:11+ from werkzeug.routing import Rule12 13+14 class Request(RequestBase):15 """The request object used by default in Flask. Remembers the16 matched endpoint and view arguments.17 17 unmodified lines35 #: :exc:`~werkzeug.exceptions.MethodNotAllowed`)36 #: because the request was never internally bound.37 #:38 #: .. versionadded:: 0.634- url_rule = None39+ url_rule: t.Optional["Rule"] = None40 41 #: A dict of view arguments that matched the request. If an exception42 #: happened when matching, this will be ``None``.38- view_args = None43+ view_args: t.Optional[t.Dict[str, t.Any]] = None44 45 #: If matching the URL failed, this is the exception that will be46 #: raised / was raised as part of the request handling. This is47 #: usually a :exc:`~werkzeug.exceptions.NotFound` exception or48 #: something similar.44- routing_exception = None49+ routing_exception: t.Optional[Exception] = None50 51 @property47- def max_content_length(self):52+ def max_content_length(self) -> t.Optional[int]: # type: ignore53 """Read-only view of the ``MAX_CONTENT_LENGTH`` config key."""54 if current_app:55 return current_app.config["MAX_CONTENT_LENGTH"]56+ else:57+ return None58 59 @property53- def endpoint(self):60+ def endpoint(self) -> t.Optional[str]:61 """The endpoint that matched the request. This in combination with62 :attr:`view_args` can be used to reconstruct the same or a63 modified URL. If an exception happened when matching, this will64 be ``None``.65 """66 if self.url_rule is not None:67 return self.url_rule.endpoint68+ else:69+ return None70 71 @property63- def blueprint(self):72+ def blueprint(self) -> t.Optional[str]:73 """The name of the current blueprint"""74 if self.url_rule and "." in self.url_rule.endpoint:75 return self.url_rule.endpoint.rsplit(".", 1)[0]76+ else:77+ return None78 68- def _load_form_data(self):79+ def _load_form_data(self) -> None:80 RequestBase._load_form_data(self)81 82 # In debug mode we're replacing the files multidict with an ad-hoc83 # subclass that raises a different error for key errors.6 unmodified lines90 from .debughelpers import attach_enctype_error_multidict91 92 attach_enctype_error_multidict(self)93 83- def on_json_loading_failed(self, e):94+ def on_json_loading_failed(self, e: Exception) -> t.NoReturn:95 if current_app and current_app.debug:96 raise BadRequest(f"Failed to decode JSON object: {e}")97 98 raise BadRequest()21 unmodified lines120 121 json_module = json122 123 @property113- def max_cookie_size(self):124+ def max_cookie_size(self) -> int: # type: ignore125 """Read-only view of the :data:`MAX_COOKIE_SIZE` config key.126 127 See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in128 Werkzeug's docs.6 unmodified linesmodified:CHANGES.rst+1 added
75 unmodified lines76 - ``flask shell`` sets up tab and history completion like the default77 ``python`` shell if ``readline`` is installed. :issue:`3941`78 - ``helpers.total_seconds()`` is deprecated. Use79 ``timedelta.total_seconds()`` instead. :pr:`3962`80+- Add type hinting. :pr:`3973`.81 82 83 Version 1.1.284 -------------1011 unmodified linesmodified:MANIFEST.in+1 added
5 unmodified lines6 graft docs7 prune docs/_build8 graft examples9 graft tests10+include src/flask/py.typed11 global-exclude *.pycmodified:setup.cfg+27 added
83 unmodified lines84 max-line-length = 8085 per-file-ignores =86 # __init__ module exports names87 src/flask/__init__.py: F40188+89+[mypy]90+files = src/flask91+python_version = 3.692+allow_redefinition = True93+disallow_subclassing_any = True94+# disallow_untyped_calls = True95+# disallow_untyped_defs = True96+# disallow_incomplete_defs = True97+no_implicit_optional = True98+local_partial_types = True99+# no_implicit_reexport = True100+strict_equality = True101+warn_redundant_casts = True102+warn_unused_configs = True103+warn_unused_ignores = True104+# warn_return_any = True105+# warn_unreachable = True106+107+[mypy-asgiref.*]108+ignore_missing_imports = True109+110+[mypy-blinker.*]111+ignore_missing_imports = True112+113+[mypy-dotenv.*]114+ignore_missing_imports = Truemodified:tox.ini+5 added
1 [tox]2 envlist =3 py{39,38,37,36,py3}4 style5+ typing6 docs7 skip_missing_interpreters = true8 9 [testenv]14 unmodified lines24 deps = pre-commit25 skip_install = true26 commands = pre-commit run --all-files --show-diff-on-failure27 28+[testenv:typing]29+deps = -r requirements/typing.txt30+commands = mypy31+32 [testenv:docs]33 deps =34 -r requirements/docs.txt35 2 unmodified lines