Skip to content
Myr

Add initial type hints

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

This should make it easier for users to correctly use Flask. The hints are from Quart.

authored by pgjones · committed by pgjones · parent f405c6f · Browse files · 20 files+820 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

20 files+820 added−461 removed

  • other:+820 added−461 removed

20 files+820 added−461 removed

modified:src/flask/json/__init__.py+37 added-20 removed
1import io2import json as _json3import typing as t4import uuid5import warnings6from datetime import date77from jinja2.utils import htmlsafe_json_dumps as _jinja_htmlsafe_dumps8from jinja2.utils import htmlsafe_json_dumps as _jinja_htmlsafe_dumps # type: ignore9from werkzeug.http import http_date1011from ..globals import current_app12from ..globals import request1314if t.TYPE_CHECKING:15 from ..app import Flask16 from ..wrappers import Response1718try:19 import dataclasses20except ImportError:21 # Python < 3.717 dataclasses = None22 dataclasses = None # type: ignore232425class JSONEncoder(_json.JSONEncoder):26 """The default JSON encoder. Handles extra types compared to the
11 unmodified lines
38 Assign a subclass of this to :attr:`flask.Flask.json_encoder` or39 :attr:`flask.Blueprint.json_encoder` to override the default.40 """4137 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 lines
52 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)575859class JSONDecoder(_json.JSONDecoder):60 """The default JSON decoder.
5 unmodified lines
66 :attr:`flask.Blueprint.json_decoder` to override the default.67 """686965def _dump_arg_defaults(kwargs, app=None):70def _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_app7677 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_encoder8283 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)899081def _load_arg_defaults(kwargs, app=None):91def _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_app9798 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_decoder103104 kwargs.setdefault("cls", cls)105 else:106 kwargs.setdefault("cls", JSONDecoder)10710894def dumps(obj, app=None, **kwargs):109def dumps(obj: t.Any, app: t.Optional["Flask"] = None, **kwargs: t.Any) -> str:110 """Serialize an object to a string of JSON.111112 Takes the same arguments as the built-in :func:`json.dumps`, with113 some defaults from application configuration.
21 unmodified lines
135 stacklevel=2,136 )137138 if isinstance(rv, str):124 return rv.encode(encoding)139 return rv.encode(encoding) # type: ignore140141 return rv142143129def dump(obj, fp, app=None, **kwargs):144def 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.148149 Takes the same arguments as the built-in :func:`json.dump`, with150 some defaults from application configuration.
15 unmodified lines
166 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: ignore171172 if show_warning:173 warnings.warn(174 "Writing to a binary file, and the 'encoding' argument, is"
4 unmodified lines
179180 _json.dump(obj, fp, **kwargs)181182166def loads(s, app=None, **kwargs):183def loads(s: str, app: t.Optional["Flask"] = None, **kwargs: t.Any) -> t.Any:184 """Deserialize an object from a string of JSON.185186 Takes the same arguments as the built-in :func:`json.loads`, with187 some defaults from application configuration.
27 unmodified lines
215216 return _json.loads(s, **kwargs)217218202def load(fp, app=None, **kwargs):219def 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.221222 Takes the same arguments as the built-in :func:`json.load`, with223 some defaults from application configuration.
19 unmodified lines
243 stacklevel=2,244 )245246 if isinstance(fp.read(0), bytes):230 fp = io.TextIOWrapper(fp, encoding)247 fp = io.TextIOWrapper(fp, encoding) # type: ignore248249 return _json.load(fp, **kwargs)250251235def htmlsafe_dumps(obj, **kwargs):252def 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 lines
272 """273 return _jinja_htmlsafe_dumps(obj, dumps=dumps, **kwargs)274275259def htmlsafe_dump(obj, fp, **kwargs):276def 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))282283267def jsonify(*args, **kwargs):284def 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.287288 Uses :func:`dumps` to serialize the data, but ``args`` and
62 unmodified lines
modified:src/flask/json/tag.py+42 added-36 removed
38 unmodified lines
39 return OrderedDict(value)4041 app.session_interface.serializer.register(TagOrderedDict, index=0)42"""43import typing as t44from base64 import b64decode45from base64 import b64encode46from datetime import datetime47from uuid import UUID
12 unmodified lines
60 __slots__ = ("serializer",)6162 #: 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] = None6565 def __init__(self, serializer):66 def __init__(self, serializer: "TaggedJSONSerializer") -> None:67 """Create a tagger for the given serializer."""68 self.serializer = serializer6969 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 NotImplementedError7373 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 NotImplementedError7878 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 NotImplementedError8383 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 lines
9697 __slots__ = ()98 key = " di"9999 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 )106106 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])}110110 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]}114115116class PassDict(JSONTag):117 __slots__ = ()118118 def check(self, value):119 def check(self, value: t.Any) -> bool:120 return isinstance(value, dict)121121 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 lines
130class TagTuple(JSONTag):131 __slots__ = ()132 key = " t"133133 def check(self, value):134 def check(self, value: t.Any) -> bool:135 return isinstance(value, tuple)136136 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]139139 def to_python(self, value):140 def to_python(self, value: t.Any) -> t.Any:141 return tuple(value)142143144class PassList(JSONTag):145 __slots__ = ()146146 def check(self, value):147 def check(self, value: t.Any) -> bool:148 return isinstance(value, list)149149 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]152153 tag = to_json154
1 unmodified line
156class TagBytes(JSONTag):157 __slots__ = ()158 key = " b"159159 def check(self, value):160 def check(self, value: t.Any) -> bool:161 return isinstance(value, bytes)162162 def to_json(self, value):163 def to_json(self, value: t.Any) -> t.Any:164 return b64encode(value).decode("ascii")165165 def to_python(self, value):166 def to_python(self, value: t.Any) -> t.Any:167 return b64decode(value)168169170class TagMarkup(JSONTag):
3 unmodified lines
174175 __slots__ = ()176 key = " m"177177 def check(self, value):178 def check(self, value: t.Any) -> bool:179 return callable(getattr(value, "__html__", None))180180 def to_json(self, value):181 def to_json(self, value: t.Any) -> t.Any:182 return str(value.__html__())183183 def to_python(self, value):184 def to_python(self, value: t.Any) -> t.Any:185 return Markup(value)186187188class TagUUID(JSONTag):189 __slots__ = ()190 key = " u"191191 def check(self, value):192 def check(self, value: t.Any) -> bool:193 return isinstance(value, UUID)194194 def to_json(self, value):195 def to_json(self, value: t.Any) -> t.Any:196 return value.hex197197 def to_python(self, value):198 def to_python(self, value: t.Any) -> t.Any:199 return UUID(value)200201202class TagDateTime(JSONTag):203 __slots__ = ()204 key = " d"205205 def check(self, value):206 def check(self, value: t.Any) -> bool:207 return isinstance(value, datetime)208208 def to_json(self, value):209 def to_json(self, value: t.Any) -> t.Any:210 return http_date(value)211211 def to_python(self, value):212 def to_python(self, value: t.Any) -> t.Any:213 return parse_date(value)214215216class TaggedJSONSerializer:
25 unmodified lines
242 TagUUID,243 TagDateTime,244 ]245245 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] = []249250 for cls in self.default_tags:251 self.register(cls)252252 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.260261 :param tag_class: tag class to register. Will be instantiated with this262 serializer instance.
19 unmodified lines
282 self.order.append(tag)283 else:284 self.order.insert(index, tag)285280 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)291292 return value293288 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 lines
302 return value303304 return self.tags[key].to_python(value[key])305300 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=(",", ":"))309304 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
1import functools2import inspect3import logging4import os5import sys6import typing as t7import weakref8from datetime import timedelta9from itertools import chain10from threading import Lock11from types import TracebackType1213from werkzeug.datastructures import Headers14from werkzeug.datastructures import ImmutableDict15from werkzeug.exceptions import BadRequest
1 unmodified line
17from werkzeug.exceptions import HTTPException18from werkzeug.exceptions import InternalServerError19from werkzeug.routing import BuildError20from werkzeug.routing import Map21from werkzeug.routing import MapAdapter22from werkzeug.routing import RequestRedirect23from werkzeug.routing import RoutingException24from werkzeug.routing import Rule25from werkzeug.wrappers import Response as BaseResponse
30 unmodified lines
56from .signals import request_started57from .signals import request_tearing_down58from .templating import DispatchingJinjaLoader59from .templating import Environment60from .typing import AfterRequestCallable61from .typing import BeforeRequestCallable62from .typing import ErrorHandlerCallable63from .typing import ResponseReturnValue64from .typing import TeardownCallable65from .typing import TemplateContextProcessorCallable66from .typing import TemplateFilterCallable67from .typing import TemplateGlobalCallable68from .typing import TemplateTestCallable69from .typing import URLDefaultCallable70from .typing import URLValuePreprocessorCallable71from .wrappers import Request72from .wrappers import Response7374if t.TYPE_CHECKING:75 from .blueprints import Blueprint76 from .testing import FlaskClient77 from .testing import FlaskCliRunner7879if sys.version_info >= (3, 8):80 iscoroutinefunction = inspect.iscoroutinefunction81else:8264 def iscoroutinefunction(func):83 def iscoroutinefunction(func: t.Any) -> bool:84 while inspect.ismethod(func):85 func = func.__func__8687 while isinstance(func, functools.partial):
1 unmodified line
8990 return inspect.iscoroutinefunction(func)919274def _make_timedelta(value):93def _make_timedelta(value: t.Optional[timedelta]) -> t.Optional[timedelta]:94 if value is None or isinstance(value, timedelta):95 return value9697 return timedelta(seconds=value)
215 unmodified lines
313 #: .. versionchanged:: 1.1.0314 #: This is a ``dict`` instead of an ``ImmutableDict`` to allow315 #: easier configuration.316 #:298 jinja_options = {}317 jinja_options: dict = {}318319 #: Default configuration parameters.320 default_config = ImmutableDict(321 {
43 unmodified lines
365366 #: 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"]] = None370371 #: 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"]] = None378379 #: the session interface to use. By default an instance of380 #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.381 #:
1 unmodified line
383 session_interface = SecureCookieSessionInterface()384385 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 lines
427 #: 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 ] = []434435 #: 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] = []441442 #: 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] = []449450 #: 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]]] = []455456 #: 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"] = {}463464 #: 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 lines
469 #: 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 = {}474475 #: 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 lines
512 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 )518519 # 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.name522502 def _is_setup_finished(self):523 def _is_setup_finished(self) -> bool:524 return self.debug and self._got_first_request525526 @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 overridden
8 unmodified lines
540 return os.path.splitext(os.path.basename(fn))[0]541 return self.import_name542543 @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.547548 .. versionadded:: 0.7
3 unmodified lines
552 return rv553 return self.testing or self.debug554555 @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 lines
565 return rv566 return self.debug567568 @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`.572573 In debug mode, the logger's :attr:`~logging.Logger.level` will
18 unmodified lines
592 """593 return create_logger(self)594595 @locked_cached_property575 def jinja_env(self):596 def jinja_env(self) -> Environment:597 """The Jinja environment used to load templates.598599 The environment is created the first time this property is600 accessed. Changing :attr:`jinja_options` after that will have no
1 unmodified line
602 """603 return self.create_jinja_environment()604605 @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.609610 .. versionadded:: 0.8611 """612 return self._got_first_request613593 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 path
8 unmodified lines
627 defaults["ENV"] = get_env()628 defaults["DEBUG"] = get_debug_flag()629 return self.config_class(root_path, defaults)630610 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 lines
640 if prefix is None:641 return os.path.join(package_path, "instance")642 return os.path.join(prefix, "var", f"{self.name}-instance")643623 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 lines
653 """654 return open(os.path.join(self.instance_path, resource), mode)655656 @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`.660661 This attribute can be configured with :data:`TEMPLATES_AUTO_RELOAD`. If
6 unmodified lines
668 rv = self.config["TEMPLATES_AUTO_RELOAD"]669 return rv if rv is not None else self.debug670671 @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"] = value674654 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 lines
703 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 rv709689 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 lines
719 .. versionadded:: 0.7720 """721 return DispatchingJinjaLoader(self)722702 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`.726727 .. versionadded:: 0.5
1 unmodified line
729 if filename is None:730 return True731 return filename.endswith((".html", ".htm", ".xml", ".xhtml"))732712 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 values
2 unmodified lines
740741 :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 lines
756 # easier add new variables in context processors without breaking757 # existing views.758 context.update(orig_ctx)759737 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 lines
780 #: Default: ``'production'``781 env = ConfigAttribute("ENV")782783 @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 is
8 unmodified lines
797 """798 return self.config["DEBUG"]799800 @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_reload804782 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.814815 Do not use ``run()`` in a production setting. It is not intended to816 meet security and performance requirements for a production server.
99 unmodified lines
916917 from werkzeug.serving import run_simple918919 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 = False926897 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`.930931 Note that if you are testing for assertions or exceptions in your
44 unmodified lines
976 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 )984953 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`.988989 Returns an instance of :attr:`test_cli_runner_class`, by default
4 unmodified lines
994 """995 cls = self.test_cli_runner_class996997 if cls is None:966 from .testing import FlaskCliRunner as cls998 from .testing import FlaskCliRunner as cls # type: ignore999968 return cls(self, **kwargs)1000 return cls(self, **kwargs) # type: ignore10011002 @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 lines
1020 .. versionadded:: 0.71021 """1022 blueprint.register(self, options)1023992 def iter_blueprints(self):1024 def iter_blueprints(self) -> t.ValuesView["Blueprint"]:1025 """Iterates over all blueprints by the order they were registered.10261027 .. versionadded:: 0.111028 """
1 unmodified line
10301031 @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)10441045 # if the methods are not given and the view_func object knows its
28 unmodified lines
1074 # Add the required methods now.1075 methods |= required_methods10761077 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: ignore10791080 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)10911092 @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 lines
1102 :param name: the optional name of the filter, otherwise the1103 function name will be used.1104 """11051074 def decorator(f):1106 def decorator(f: TemplateFilterCallable) -> TemplateFilterCallable:1107 self.add_template_filter(f, name=name)1108 return f11091110 return decorator11111112 @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.11181119 :param name: the optional name of the filter, otherwise the
1 unmodified line
1121 """1122 self.jinja_env.filters[name or f.__name__] = f11231124 @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 lines
1141 :param name: the optional name of the test, otherwise the1142 function name will be used.1143 """11441111 def decorator(f):1145 def decorator(f: TemplateTestCallable) -> TemplateTestCallable:1146 self.add_template_test(f, name=name)1147 return f11481149 return decorator11501151 @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.11571158 .. versionadded:: 0.10
3 unmodified lines
1162 """1163 self.jinja_env.tests[name or f.__name__] = f11641165 @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 lines
1177 :param name: the optional name of the global function, otherwise the1178 function name will be used.1179 """11801145 def decorator(f):1181 def decorator(f: TemplateGlobalCallable) -> TemplateGlobalCallable:1182 self.add_template_global(f, name=name)1183 return f11841185 return decorator11861187 @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.11931194 .. versionadded:: 0.10
3 unmodified lines
1198 """1199 self.jinja_env.globals[name or f.__name__] = f12001201 @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.12051206 The function will be called without any arguments and its return
4 unmodified lines
1211 self.before_first_request_funcs.append(self.ensure_sync(f))1212 return f12131214 @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 lines
1244 self.teardown_appcontext_funcs.append(self.ensure_sync(f))1245 return f12461247 @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.12501251 .. versionadded:: 0.111252 """1253 self.shell_context_processors.append(f)1254 return f12551218 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 lines
1272 handler = handler_map.get(cls)12731274 if handler is not None:1275 return handler1276 return None12771239 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 lines
1309 if handler is None:1310 return e1311 return handler(e)13121272 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 lines
1344 return isinstance(e, BadRequest)13451346 return False13471307 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 either
21 unmodified lines
1376 raise13771378 return handler(e)13791337 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 lines
14161417 raise e14181419 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)14231424 if handler is not None:1425 server_error = handler(server_error)14261427 return self.finalize_request(server_error, from_error_handler=True)14281385 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 lines
1442 self.logger.error(1443 f"Exception on {request.path} [{request.method}]", exc_info=exc_info1444 )14451397 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 lines
1455 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: ignore14601461 from .debughelpers import FormDataRoutingRedirect14621463 raise FormDataRoutingRedirect(request)14641416 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 lines
1485 return self.make_default_options_response()1486 # otherwise dispatch to the handler for that endpoint1487 return self.view_functions[rule.endpoint](**req.view_args)14881440 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 lines
1502 except Exception as e:1503 rv = self.handle_user_exception(e)1504 return self.finalize_request(rv)15051457 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 lines
1531 "Request finalizing failed with an error while handling an error"1532 )1533 return response15341482 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 lines
1547 for func in self.before_first_request_funcs:1548 func()1549 self._got_first_request = True15501498 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 lines
1560 rv = self.response_class()1561 rv.allow.update(methods)1562 return rv15631511 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 line
1570 .. versionadded:: 0.101571 """1572 return False15731521 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 lines
1584 return run_async(func)15851586 return func15871535 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`.15911592 :param rv: the return value from the view function. The view function
79 unmodified lines
1672 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 lines
1688 " dict, tuple, Response instance, or WSGI"1689 f" callable, but it was a {type(rv).__name__}."1690 )16911692 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 = status16991700 # extend existing headers with provided headers
1 unmodified line
1702 rv.headers.update(headers)17031704 return rv17051652 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 lines
1742 script_name=self.config["APPLICATION_ROOT"],1743 url_scheme=self.config["PREFERRED_URL_SCHEME"],1744 )17451746 return None17471690 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.17521753 .. 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)17611704 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 lines
1781 raise17821783 raise error17841725 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 lines
1792 value is handled as if it was the return value from the view, and1793 further request handling is stopped.1794 """17951736 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)18041743 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 rv18131814 return None18151752 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 lines
1826 :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 lines
1838 if not self.session_interface.is_null_session(ctx.session):1839 self.session_interface.save_session(self, ctx.session, response)1840 return response18411778 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.18471848 This calls all functions decorated with
14 unmodified lines
1863 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)18761809 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.18811882 When handling a request, the application context is popped1883 after the request context. See :meth:`do_teardown_request`.
12 unmodified lines
1896 for func in reversed(self.teardown_appcontext_funcs):1897 func(exc)1898 appcontext_tearing_down.send(self, exc=exc)18991830 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 lines
1917 .. versionadded:: 0.91918 """1919 return AppContext(self)19201851 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 lines
1933 :param environ: a WSGI environment1934 """1935 return RequestContext(self, environ)19361867 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 lines
1989 return self.request_context(builder.get_environ())1990 finally:1991 builder.close()19921923 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 lines
2015 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 lines
2032 if self.should_ignore_error(error):2033 error = None2034 ctx.auto_pop(error)20351966 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)20421973 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
1import typing as t2from collections import defaultdict3from functools import update_wrapper45from .scaffold import _endpoint_from_view_func6from .scaffold import _sentinel7from .scaffold import Scaffold8from .typing import AfterRequestCallable9from .typing import BeforeRequestCallable10from .typing import ErrorHandlerCallable11from .typing import TeardownCallable12from .typing import TemplateContextProcessorCallable13from .typing import TemplateFilterCallable14from .typing import TemplateGlobalCallable15from .typing import TemplateTestCallable16from .typing import URLDefaultCallable17from .typing import URLValuePreprocessorCallable1819if t.TYPE_CHECKING:20 from .app import Flask2122DeferredSetupFunction = t.Callable[["BlueprintSetupState"], t.Callable]232425class 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 """3116 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 = app4142 #: a reference to the blueprint that created this setup state.
30 unmodified lines
73 #: 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", ()))7655 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 lines
91 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 lines
169 json_decoder = None170171 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 lines
190 )191 self.name = name192 self.url_prefix = url_prefix193 self.subdomain = subdomain166 self.deferred_functions = []194 self.deferred_functions: t.List[DeferredSetupFunction] = []195196 if url_defaults is None:197 url_defaults = {}198199 self.url_values_defaults = url_defaults200 self.cli_group = cli_group173 self._blueprints = []201 self._blueprints: t.List[t.Tuple["Blueprint", dict]] = []202175 def _is_setup_finished(self):203 def _is_setup_finished(self) -> bool:204 return self.warn_on_modifications and self._got_registered_once205178 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 lines
220 )221 )222 self.deferred_functions.append(func)223196 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 """230203 def wrapper(state):231 def wrapper(state: BlueprintSetupState) -> None:232 if state.first_registration:233 func(state)234235 return self.record(update_wrapper(wrapper, func))236209 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)245216 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.250251 .. versionadded:: 2.0252 """253 self._blueprints.append((blueprint, options))254225 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 lines
356 bp_options["url_prefix"] = url_prefix357 bp_options["name_prefix"] = options.get("name_prefix", "") + self.name + "."358 blueprint.register(app, bp_options)359330 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 lines
374 "." 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))377342 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.381382 :param name: the optional name of the filter, otherwise the383 function name will be used.384 """385350 def decorator(f):386 def decorator(f: TemplateFilterCallable) -> TemplateFilterCallable:387 self.add_app_template_filter(f, name=name)388 return f389390 return decorator391356 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.398399 :param name: the optional name of the filter, otherwise the400 function name will be used.401 """402365 def register_template(state):403 def register_template(state: BlueprintSetupState) -> None:404 state.app.jinja_env.filters[name or f.__name__] = f405406 self.record_once(register_template)407370 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.411412 .. versionadded:: 0.10
1 unmodified line
414 :param name: the optional name of the test, otherwise the415 function name will be used.416 """417380 def decorator(f):418 def decorator(f: TemplateTestCallable) -> TemplateTestCallable:419 self.add_app_template_test(f, name=name)420 return f421422 return decorator423386 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 lines
433 :param name: the optional name of the test, otherwise the434 function name will be used.435 """436397 def register_template(state):437 def register_template(state: BlueprintSetupState) -> None:438 state.app.jinja_env.tests[name or f.__name__] = f439440 self.record_once(register_template)441402 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.445446 .. versionadded:: 0.10
1 unmodified line
448 :param name: the optional name of the global, otherwise the449 function name will be used.450 """451412 def decorator(f):452 def decorator(f: TemplateGlobalCallable) -> TemplateGlobalCallable:453 self.add_app_template_global(f, name=name)454 return f455456 return decorator457418 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 lines
467 :param name: the optional name of the global, otherwise the468 function name will be used.469 """470429 def register_template(state):471 def register_template(state: BlueprintSetupState) -> None:472 state.app.jinja_env.globals[name or f.__name__] = f473474 self.record_once(register_template)475434 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 lines
483 )484 )485 return f486445 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 f497454 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 lines
505 )506 )507 return f508465 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 line
515 lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)516 )517 return f518475 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 f529484 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 """534489 def decorator(f):535 def decorator(f: ErrorHandlerCallable) -> ErrorHandlerCallable:536 self.record_once(lambda s: s.app.errorhandler(code)(f))537 return f538539 return decorator540495 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 f549502 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 f556509 def ensure_sync(self, f):557 def ensure_sync(self, f: t.Callable) -> t.Callable:558 """Ensure the function is synchronous.559560 Override if you would like custom async to sync behaviour in561 this blueprint. Otherwise the app's
5 unmodified lines
modified:src/flask/cli.py+10 added-7 removed
25 unmodified lines
2627try:28 import ssl29except ImportError:30 ssl = None30 ssl = None # type: ignore313233class NoAppException(click.UsageError):34 """Raised if an application cannot be found or loaded."""
824 unmodified lines
859860861@click.command("shell", short_help="Run a shell in the app context.")862@with_appcontext863def shell_command():863def 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 lines
876 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 = {}881882 # Support the regular Python interpreter startup script if someone883 # is using it.884 startup = os.environ.get("PYTHONSTARTUP")
36 unmodified lines
921 ),922)923@click.option("--all-methods", is_flag=True, help="Show HEAD and OPTIONS methods.")924@with_appcontext925def routes_command(sort, all_methods):925def routes_command(sort: str, all_methods: bool) -> None:926 """Show all registered routes with endpoints and methods."""927928 rules = list(current_app.url_map.iter_rules())929 if not rules:
4 unmodified lines
934935 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: ignore939940 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 ]944945 headers = ("Endpoint", "Methods", "Rule")946 widths = (947 max(len(rule.endpoint) for rule in rules),
29 unmodified lines
977 )978)979980978def main():981def main() -> None:982 # TODO omit sys.argv once https://github.com/pallets/click/issues/536 is fixed983 cli.main(args=sys.argv[1:])984985
2 unmodified lines
modified:src/flask/config.py+28 added-26 removed
1import errno2import os3import types4import typing as t56from werkzeug.utils import import_string789class ConfigAttribute:10 """Makes an attribute forward to the config"""1111 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_converter1515 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 rv2323 def __set__(self, obj, value):24 def __set__(self, obj: t.Any, value: t.Any) -> None:25 obj.config[self.__name__] = value262728class Config(dict):
39 unmodified lines
68 the application's :attr:`~flask.Flask.root_path`.69 :param defaults: an optional dictionary of default values70 """7171 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_path7575 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 lines
96 " file"97 )98 return self.from_pyfile(rv, silent=silent)9999 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 lines
124 raise125 self.from_object(d)126 return True127127 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:131132 - a string: in this case the object with that name will be imported
29 unmodified lines
162 for key in dir(obj):163 if key.isupper():164 self[key] = getattr(obj, key)165165 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 lines
201 raise202203 return self.from_mapping(obj)204199 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.210211 .. 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 True221222 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::227228 app.config['IMAGE_STORE_TYPE'] = 'fs'
32 unmodified lines
261 key = key.lower()262 rv[key] = v263 return rv264263 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
1import sys2import typing as t3from functools import update_wrapper4from types import TracebackType56from werkzeug.exceptions import HTTPException78from .globals import _app_ctx_stack9from .globals import _request_ctx_stack10from .signals import appcontext_popped11from .signals import appcontext_pushed12from .typing import AfterRequestCallable1314if t.TYPE_CHECKING:15 from .app import Flask16 from .sessions import SessionMixin17 from .wrappers import Request181920# a singleton sentinel value for parameter defaults21_sentinel = object()2223
16 unmodified lines
4041 .. versionadded:: 0.1042 """4336 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`.4748 :param name: Name of attribute to get.
2 unmodified lines
51 .. versionadded:: 0.1052 """53 return self.__dict__.get(name, default)5447 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`.5758 :param name: Name of attribute to pop.59 :param default: Value to return if the attribute is not present,
5 unmodified lines
65 return self.__dict__.pop(name)66 else:67 return self.__dict__.pop(name, default)6861 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`.7273 :param name: Name of attribute to get.
3 unmodified lines
77 .. versionadded:: 0.1178 """79 return self.__dict__.setdefault(name, default)8073 def __contains__(self, item):81 def __contains__(self, item: t.Any) -> bool:82 return item in self.__dict__8376 def __iter__(self):84 def __iter__(self) -> t.Iterator:85 return iter(self.__dict__)8679 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)929386def after_this_request(f):94def 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 lines
115 _request_ctx_stack.top._after_request_functions.append(f)116 return f117118111def copy_current_request_context(f):119def 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 also
31 unmodified lines
155156 return update_wrapper(wrapper, f)157158151def has_request_context():159def 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 lines
187 """188 return _request_ctx_stack.top is not None189190183def has_app_context():191def 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 lines
206 but the application is not on top of the individual application207 context.208 """209202 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()214215 # Like request context, app contexts can be pushed multiple times216 # but there a basic "refcount" is enough to track them.217 self._refcnt = 0218211 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)224217 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 lines
234 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)237230 def __enter__(self):238 def __enter__(self) -> "AppContext":239 self.push()240 return self241234 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)246247248class RequestContext:
25 unmodified lines
274 sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in275 that situation, otherwise your unittests will leak memory.276 """277268 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 = request
8 unmodified lines
297 # 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"]] = []302303 # indicator if the context was preserved. Next time another context304 # is pushed the preserved context is popped.305 self.preserved = False
4 unmodified lines
310311 # 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] = []315316 @property301 def g(self):317 def g(self) -> AppContext:318 return _app_ctx_stack.top.g319320 @g.setter305 def g(self, value):321 def g(self, value: AppContext) -> None:322 _app_ctx_stack.top.g = value323308 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 the
11 unmodified lines
340 request=self.request,341 session=self.session,342 )343328 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 = e353338 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 that
31 unmodified lines
390391 if self.session is None:392 self.session = session_interface.make_null_session(self.app)393378 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 lines
429 assert (430 rv is self431 ), f"Popped wrong request context. ({rv!r} instead of {self!r})"432417 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)441426 def __enter__(self):442 def __enter__(self) -> "RequestContext":443 self.push()444 return self445430 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)455438 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
1import os2import typing as t3from warnings import warn45from .app import Flask6from .blueprints import Blueprint
85 unmodified lines
92 newcls.__module__ = oldcls.__module__93 request.files.__class__ = newcls949595def _dump_loader_info(loader):96def _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 continue
8 unmodified lines
109 continue110 yield f"{key}: {value!r}"111112112def explain_template_loading_attempts(app, template, attempts):113def 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 = None
39 unmodified lines
157158 app.logger.info("\n".join(info))159160160def explain_ignored_app_run():161def 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 lines
modified:src/flask/globals.py+10 added-4 removed
1import typing as t2from functools import partial34from werkzeug.local import LocalProxy5from werkzeug.local import LocalStack67if t.TYPE_CHECKING:8 from .app import Flask9 from .ctx import AppContext10 from .sessions import SessionMixin11 from .wrappers import Request1213_request_ctx_err_msg = """\14Working outside of request context.15
34 unmodified lines
5051# context locals52_request_ctx_stack = LocalStack()53_app_ctx_stack = LocalStack()48current_app = LocalProxy(_find_app)49request = LocalProxy(partial(_lookup_req_object, "request"))50session = LocalProxy(partial(_lookup_req_object, "session"))51g = LocalProxy(partial(_lookup_app_object, "g"))54current_app: "Flask" = LocalProxy(_find_app) # type: ignore55request: "Request" = LocalProxy(partial(_lookup_req_object, "request")) # type: ignore56session: "SessionMixin" = LocalProxy(partial(_lookup_req_object, "session")) # type: ignore # noqa: B95057g: "AppContext" = LocalProxy(partial(_lookup_app_object, "g")) # type: ignore
modified:src/flask/helpers.py+45 added-29 removed
1import os2import socket3import typing as t4import warnings5from datetime import timedelta6from functools import update_wrapper7from functools import wraps8from threading import RLock9
9 unmodified lines
19from .globals import request20from .globals import session21from .signals import message_flashed2223if t.TYPE_CHECKING:24 from .wrappers import Response252622def get_env():27def 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"333430def get_debug_flag():35def 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 lines
4546 return val.lower() not in ("0", "false", "no")474844def get_load_dotenv(default=True):49def 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 lines
6061 return val.lower() in ("0", "false", "no")626359def stream_with_context(generator_or_function):64def 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 bound
26 unmodified lines
9798 .. versionadded:: 0.999 """100 try:94 gen = iter(generator_or_function)101 gen = iter(generator_or_function) # type: ignore102 except TypeError:10397 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)107101 return update_wrapper(decorator, generator_or_function)108 return update_wrapper(decorator, generator_or_function) # type: ignore109103 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 lines
126 try:127 yield from gen128 finally:129 if hasattr(gen, "close"):123 gen.close()130 gen.close() # type: ignore131132 # 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 the
2 unmodified lines
137 next(wrapped_g)138 return wrapped_g139140134def make_response(*args):141def 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 return
40 unmodified lines
186 args = args[0]187 return current_app.make_response(args)188189183def url_for(endpoint, **values):190def url_for(endpoint: str, **values: t.Any) -> str:191 """Generates a URL to the given endpoint with the method provided.192193 Variable arguments that are unknown to the target endpoint are appended194 to the generated URL as query arguments. If the value of a query argument
142 unmodified lines
337 rv += f"#{url_quote(anchor)}"338 return rv339340334def get_template_attribute(template_name, attribute):341def 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 lines
359 """360 return getattr(current_app.jinja_env.get_template(template_name).module, attribute)361362356def flash(message, category="message"):363def 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 lines
385 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 )393394386def get_flashed_messages(with_categories=False, category_filter=()):395def 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 will
216 unmodified lines
618 )619 )620621611def safe_join(directory, *pathnames):622def 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.625626 :param directory: The trusted base directory.
14 unmodified lines
641642 return path643644634def send_from_directory(directory, path, **kwargs):645def send_from_directory(directory: str, path: str, **kwargs: t.Any) -> "Response":646 """Send a file from within a directory using :func:`send_file`.647648 .. code-block:: python649
21 unmodified lines
671 pass some Flask-specific arguments.672673 .. 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 )678679
5 unmodified lines
685 .. versionchanged:: 2.0686 Inherits from Werkzeug's ``cached_property`` (and ``property``).687 """688678 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()697682 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 self701702 with self.lock:703 return super().__get__(obj, type=type)704689 def __set__(self, obj, value):705 def __set__(self, obj: object, value: t.Any) -> None:706 with self.lock:707 super().__set__(obj, value)708693 def __delete__(self, obj):709 def __delete__(self, obj: object) -> None:710 with self.lock:711 super().__delete__(obj)712713698def total_seconds(td):714def total_seconds(td: timedelta) -> int:715 """Returns the total seconds from a timedelta object.716717 :param timedelta td: the timedelta to be converted in seconds718
12 unmodified lines
731 )732 return td.days * 60 * 60 * 24 + td.seconds733734719def is_ip(value):735def is_ip(value: str) -> bool:736 """Determine if the given string is an IP address.737738 :param value: value to check739 :type value: str
11 unmodified lines
751752 return False753754739def run_async(func):755def 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 lines
767 "Async cannot be used with this combination of Python & Greenlet versions."768 )769770 @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.773774 This is similar to the copy_current_xxx_context functions in the775 ctx module, except it has an async inner.
3 unmodified lines
779 if _request_ctx_stack.top is not None:780 ctx = _request_ctx_stack.top.copy()781782 @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.785786 This is required as the function must be awaited within the787 context. Only calling ``func`` (as per the
7 unmodified lines
795 return await func(*a, **k)796797 return async_to_sync(inner)(*args, **kwargs)798783 outer._flask_sync_wrapper = True799 outer._flask_sync_wrapper = True # type: ignore800 return outer
modified:src/flask/logging.py+9 added-5 removed
1import logging2import sys3import typing as t45from werkzeug.local import LocalProxy67from .globals import request89if t.TYPE_CHECKING:10 from .app import Flask111213@LocalProxy10def wsgi_errors_stream():14def 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``.1718 If you configure your own :class:`logging.StreamHandler`, you may want to
3 unmodified lines
22 """23 return request.environ["wsgi.errors"] if request else sys.stderr242522def has_level_handler(logger):26def 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 lines
3637 if not current.propagate:38 break3936 current = current.parent40 current = current.parent # type: ignore4142 return False434445#: Log messages to :func:`~flask.logging.wsgi_errors_stream` with the format46#: ``[%(asctime)s] %(levelname)s in %(module)s: %(message)s``.43default_handler = logging.StreamHandler(wsgi_errors_stream)47default_handler = logging.StreamHandler(wsgi_errors_stream) # type: ignore48default_handler.setFormatter(49 logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")50)515249def create_logger(app):53def create_logger(app: "Flask") -> logging.Logger:54 """Get the Flask app's logger and configure it if needed.5556 The logger name will be the same as57 :attr:`app.import_name <flask.Flask.name>`.
17 unmodified lines
modified:src/flask/scaffold.py+112 added-63 removed
1import importlib.util2import os3import pkgutil4import sys5import typing as t6from collections import defaultdict7from functools import update_wrapper8from json import JSONDecoder9from json import JSONEncoder1011from jinja2 import FileSystemLoader12from werkzeug.exceptions import default_exceptions13from werkzeug.exceptions import HTTPException
2 unmodified lines
16from .globals import current_app17from .helpers import locked_cached_property18from .helpers import send_from_directory19from .templating import _default_template_ctx_processor20from .typing import AfterRequestCallable21from .typing import AppOrBlueprintKey22from .typing import BeforeRequestCallable23from .typing import ErrorHandlerCallable24from .typing import TeardownCallable25from .typing import TemplateContextProcessorCallable26from .typing import URLDefaultCallable27from .typing import URLValuePreprocessorCallable2829if t.TYPE_CHECKING:30 from .wrappers import Response3132# a singleton sentinel value for parameter defaults33_sentinel = object()343522def setupmethod(f):36def 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 """4027 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 lines
73 .. versionadded:: 2.074 """7576 name: str63 _static_folder = None64 _static_url_path = None77 _static_folder: t.Optional[str] = None78 _static_url_path: t.Optional[str] = None7980 #: 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]] = None8384 #: 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]] = None8788 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_name
24 unmodified lines
123 #: 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] = {}128129 #: 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, or
6 unmodified lines
138 #: 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))146147 #: 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 are
3 unmodified lines
153 #: 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)160161 #: 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 are
3 unmodified lines
167 #: 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)174175 #: 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 a
4 unmodified lines
182 #: 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)189190 #: 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 a
4 unmodified lines
197 #: 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]})204205 #: 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 a
4 unmodified lines
212 #: :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)220221 #: 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 a
4 unmodified lines
228 #: 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)235208 def __repr__(self):236 def __repr__(self) -> str:237 return f"<{type(self).__name__} {self.name!r}>"238211 def _is_setup_finished(self):239 def _is_setup_finished(self) -> bool:240 raise NotImplementedError241242 @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 None251252 @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"\/")256257 self._static_folder = value258259 @property230 def has_static_folder(self):260 def has_static_folder(self) -> bool:261 """``True`` if :attr:`static_folder` is set.262263 .. versionadded:: 0.5264 """265 return self.static_folder is not None266267 @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.270271 If it was not configured during init, it is derived from272 :attr:`static_folder`.
4 unmodified lines
277 if self.static_folder is not None:278 basename = os.path.basename(self.static_folder)279 return f"/{basename}".rstrip("/")280281 return None282283 @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("/")287288 self._static_url_path = value289258 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.293294 By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
12 unmodified lines
307 return None308309 return int(value.total_seconds())310279 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 lines
321322 # 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 )328329 @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.334335 .. 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 None341306 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.345346 For example, if the file ``schema.sql`` is next to the file
14 unmodified lines
361 raise ValueError("Resources can only be opened for reading.")362363 return open(os.path.join(self.root_path, resource), mode)364329 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.")368369 return self.route(rule, methods=[method], **options)370335 def get(self, rule, **options):371 def get(self, rule: str, **options: t.Any) -> t.Callable:372 """Shortcut for :meth:`route` with ``methods=["GET"]``.373374 .. versionadded:: 2.0375 """376 return self._method_route("GET", rule, options)377342 def post(self, rule, **options):378 def post(self, rule: str, **options: t.Any) -> t.Callable:379 """Shortcut for :meth:`route` with ``methods=["POST"]``.380381 .. versionadded:: 2.0382 """383 return self._method_route("POST", rule, options)384349 def put(self, rule, **options):385 def put(self, rule: str, **options: t.Any) -> t.Callable:386 """Shortcut for :meth:`route` with ``methods=["PUT"]``.387388 .. versionadded:: 2.0389 """390 return self._method_route("PUT", rule, options)391356 def delete(self, rule, **options):392 def delete(self, rule: str, **options: t.Any) -> t.Callable:393 """Shortcut for :meth:`route` with ``methods=["DELETE"]``.394395 .. versionadded:: 2.0396 """397 return self._method_route("DELETE", rule, options)398363 def patch(self, rule, **options):399 def patch(self, rule: str, **options: t.Any) -> t.Callable:400 """Shortcut for :meth:`route` with ``methods=["PATCH"]``.401402 .. versionadded:: 2.0403 """404 return self._method_route("PATCH", rule, options)405370 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 lines
426 :param options: Extra options passed to the427 :class:`~werkzeug.routing.Rule` object.428 """429394 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 line
436437 @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 lines
501 :class:`~werkzeug.routing.Rule` object.502 """503 raise NotImplementedError504469 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 lines
525526 return decorator527528 @setupmethod493 def before_request(self, f):529 def before_request(self, f: BeforeRequestCallable) -> BeforeRequestCallable:530 """Register a function to run before each request.531532 For example, this can be used to open a database connection, or533 to load the logged in user from the session.
13 unmodified lines
547 self.before_request_funcs.setdefault(None, []).append(self.ensure_sync(f))548 return f549550 @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.553554 The function is called with the response object, and must return555 a response object. This allows the functions to modify or
7 unmodified lines
563 self.after_request_funcs.setdefault(None, []).append(self.ensure_sync(f))564 return f565566 @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 lines
602 self.teardown_request_funcs.setdefault(None, []).append(self.ensure_sync(f))603 return f604605 @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 f612613 @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 lines
629 self.url_value_preprocessors[None].append(f)630 return f631632 @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 f640641 @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.646647 A decorator that is used to register a function given an648 error code. Example::
21 unmodified lines
670 :param code_or_exception: the code as integer for the handler, or671 an arbitrary exception672 """673632 def decorator(f):674 def decorator(f: ErrorHandlerCallable) -> ErrorHandlerCallable:675 self.register_error_handler(code_or_exception, f)676 return f677678 return decorator679680 @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 lines
707708 self.error_handler_spec[None][code][exc_class] = self.ensure_sync(f)709710 @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.717718 :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_code
6 unmodified lines
732 return exc_class, exc_class.code733 else:734 return exc_class, None735687 def ensure_sync(self, func):736 def ensure_sync(self, func: t.Callable) -> t.Callable:737 raise NotImplementedError()738739691def _endpoint_from_view_func(view_func):740def _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__746747699def get_root_path(import_name):748def 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 lines
769 if loader is None or import_name == "__main__":770 return os.getcwd()771772 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 lines
870871 return package_path872873825def find_package(import_name):874def find_package(import_name: str):875 """Find the prefix that a package is installed under, and the path876 that it would be imported from.877878 The prefix is the directory containing the standard directory
35 unmodified lines
modified:src/flask/sessions.py+44 added-26 removed
1import hashlib2import typing as t3import warnings4from collections.abc import MutableMapping5from datetime import datetime6
3 unmodified lines
1011from .helpers import is_ip12from .json.tag import TaggedJSONSerializer1314if t.TYPE_CHECKING:15 from .app import Flask16 from .wrappers import Request, Response171819class SessionMixin(MutableMapping):20 """Expands a basic dictionary with session attributes."""2122 @property18 def permanent(self):23 def permanent(self) -> bool:24 """This reflects the ``'_permanent'`` key in the dict."""25 return self.get("_permanent", False)2627 @permanent.setter23 def permanent(self, value):28 def permanent(self, value: bool) -> None:29 self["_permanent"] = bool(value)3031 #: Some implementations can detect whether a session is newly32 #: created, but that is not guaranteed. Use with caution. The mixin
32 unmodified lines
65 #: header, which allows caching proxies to cache different pages for66 #: different users.67 accessed = False6864 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 = True7374 super().__init__(initial, on_update)7571 def __getitem__(self, key):76 def __getitem__(self, key: str) -> t.Any:77 self.accessed = True78 return super().__getitem__(key)7975 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)8379 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)8788
2 unmodified lines
91 available. Will still allow read-only access to the empty session92 but fail on setting.93 """9490 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 )10197 __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail102 __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail # type: ignore # noqa: B950103 del _fail104105106class SessionInterface:
38 unmodified lines
145 #:146 #: .. versionadded:: 0.10147 pickle_based = False148144 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 but
3 unmodified lines
157 This creates an instance of :attr:`null_session_class` by default.158 """159 return self.null_session_class()160156 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.164165 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)169165 def get_cookie_name(self, app):170 def get_cookie_name(self, app: "Flask") -> str:171 """Returns the name of the session cookie.172173 Uses ``app.session_cookie_name`` which is set to ``SESSION_COOKIE_NAME``174 """175 return app.session_cookie_name176172 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.179180 Uses ``SESSION_COOKIE_DOMAIN`` if it is configured, otherwise181 falls back to detecting the domain based on ``SERVER_NAME``.
49 unmodified lines
231232 app.config["SESSION_COOKIE_DOMAIN"] = rv233 return rv234230 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"]242238 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"]249245 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"]255251 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"]262258 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 None274267 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 is
7 unmodified lines
287 return session.modified or (288 session.permanent and app.config["SESSION_REFRESH_EACH_REQUEST"]289 )290283 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()300291 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 lines
330 #: such as datetime objects or tuples.331 serializer = session_json_serializer332 session_class = SecureCookieSession333322 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_method
4 unmodified lines
345 serializer=self.serializer,346 signer_kwargs=signer_kwargs,347 )348335 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 lines
361 return self.session_class(data)362 except BadSignature:363 return self.session_class()364349 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 lines
389 return390391 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 lines
modified:src/flask/signals.py+7 added-5 removed
1import typing as t23try:4 from blinker import Namespace56 signals_available = True7except ImportError:8 signals_available = False98 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)1314 class _FakeSignal:15 """If blinker is unavailable, create a fake class with the same
1 unmodified line
17 error on anything else. Instead of doing anything on send, it18 will just ignore the arguments and do nothing instead.19 """2019 def __init__(self, name, doc=None):21 def __init__(self, name: str, doc: t.Optional[str] = None) -> None:22 self.name = name23 self.__doc__ = doc2423 def send(self, *args, **kwargs):25 def send(self, *args: t.Any, **kwargs: t.Any) -> t.Any:26 pass2726 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 lines
modified:src/flask/templating.py+28 added-11 removed
1import typing as t23from jinja2 import BaseLoader4from jinja2 import Environment as BaseEnvironment5from jinja2 import Template6from jinja2 import TemplateNotFound78from .globals import _app_ctx_stack9from .globals import _request_ctx_stack10from .signals import before_render_template11from .signals import template_rendered1213if t.TYPE_CHECKING:14 from .app import Flask15 from .scaffold import Scaffold161711def _default_template_ctx_processor():18def _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.top
12 unmodified lines
35 knowledge of how Flask's blueprint works so that it can prepend the36 name of the blueprint to referenced templates if necessary.37 """3832 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 = app
3 unmodified lines
47 """A loader that looks for templates in the application and all48 the blueprint folders.49 """5044 def __init__(self, app):51 def __init__(self, app: "Flask") -> None:52 self.app = app5347 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)6052 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 = None6667 for srcobj, loader in self._iter_loaders(template):
12 unmodified lines
80 if trv is not None:81 return trv82 raise TemplateNotFound(template)8373 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)9381 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 line
102 loader = blueprint.jinja_loader103 if loader is not None:104 yield blueprint, loader10591 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 lines
117118 return list(result)119120106def _render(template, context, app):121def _render(template: Template, context: dict, app: "Flask") -> str:122 """Renders the template and fires the signal"""123124 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 rv128129115def render_template(template_name_or_list, **context):130def 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.135136 :param template_name_or_list: the name of the template to be
10 unmodified lines
147 ctx.app,148 )149150134def render_template_string(source, **context):151def 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.154155 :param source: the source code of the template to be
7 unmodified lines
modified:src/flask/testing.py+38 added-19 removed
1import typing as t2from contextlib import contextmanager3from copy import copy4from types import TracebackType56import werkzeug.test7from click.testing import CliRunner8from werkzeug.test import Client
2 unmodified lines
1112from . import _request_ctx_stack13from .cli import ScriptInfo14from .json import dumps as json_dumps15from .sessions import SessionMixin1617if t.TYPE_CHECKING:18 from .app import Flask19 from .wrappers import Response202122class EnvironBuilder(werkzeug.test.EnvironBuilder):23 """An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the24 application.25
16 unmodified lines
42 """4344 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_scheme
22 unmodified lines
8081 self.app = app82 super().__init__(path, base_url, *args, **kwargs)8377 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.8687 The serialization will be configured according to the config associated88 with this EnvironBuilder's ``app``.
16 unmodified lines
105106 Basic usage is outlined in the :doc:`/testing` chapter.107 """108109 application: "Flask"110 preserve_context = False111104 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 }118119 @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 lines
170 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)173164 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 = None184185 def copy_environ(other):
26 unmodified lines
212 request = builder.get_request()213 finally:214 builder.close()215201 return super().open(216 return super().open( # type: ignore217 request,218 as_tuple=as_tuple,219 buffered=buffered,220 follow_redirects=follow_redirects,221 )222208 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 self228214 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 = False233234 # Normally the request context is preserved until the next235 # request in the same thread comes. When the client exits we
13 unmodified lines
249 CLI commands. Typically created using250 :meth:`~flask.Flask.test_cli_runner`. See :ref:`testing-cli`.251 """252236 def __init__(self, app, **kwargs):253 def __init__(self, app: "Flask", **kwargs: t.Any) -> None:254 self.app = app255 super().__init__(**kwargs)256240 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 lines
added:src/flask/typing.py+46 added
1import typing as t234if t.TYPE_CHECKING:5 from werkzeug.datastructures import Headers # noqa: F4016 from wsgiref.types import WSGIApplication # noqa: F4017 from .wrappers import Response # noqa: F40189# The possible types that are directly convertible or are a Response object.10ResponseValue = t.Union[11 "Response",12 t.AnyStr,13 t.Dict[str, t.Any], # any jsonify-able dict14 t.Generator[t.AnyStr, None, None],15]16StatusCode = int1718# the possible types for an individual HTTP header19HeaderName = str20HeaderValue = t.Union[str, t.List[str], t.Tuple[str, ...]]2122# the possible types for HTTP headers23HeadersValue = t.Union[24 "Headers", t.Dict[HeaderName, HeaderValue], t.List[t.Tuple[HeaderName, HeaderValue]]25]2627# The possible types returned by a route function.28ResponseReturnValue = t.Union[29 ResponseValue,30 t.Tuple[ResponseValue, HeadersValue],31 t.Tuple[ResponseValue, StatusCode],32 t.Tuple[ResponseValue, StatusCode, HeadersValue],33 "WSGIApplication",34]3536AppOrBlueprintKey = t.Optional[str] # The App key is None, whereas blueprints are named37AfterRequestCallable = t.Callable[["Response"], "Response"]38BeforeRequestCallable = t.Callable[[], None]39ErrorHandlerCallable = t.Callable[[Exception], ResponseReturnValue]40TeardownCallable = t.Callable[[t.Optional[BaseException]], "Response"]41TemplateContextProcessorCallable = t.Callable[[], t.Dict[str, t.Any]]42TemplateFilterCallable = t.Callable[[t.Any], str]43TemplateGlobalCallable = t.Callable[[], t.Any]44TemplateTestCallable = t.Callable[[t.Any], bool]45URLDefaultCallable = t.Callable[[str, dict], None]46URLValuePreprocessorCallable = t.Callable[[t.Optional[str], t.Optional[dict]], None]
modified:src/flask/views.py+16 added-11 removed
1import typing as t23from .globals import request4from .typing import ResponseReturnValue567http_method_funcs = frozenset(8 ["get", "post", "head", "options", "delete", "put", "trace", "patch"]
32 unmodified lines
41 generated view function!42 """4344 #: A list of methods this view can handle.42 methods = None45 methods: t.Optional[t.List[str]] = None4647 #: Setting this disables or force-enables the automatic options handling.45 provide_automatic_options = None48 provide_automatic_options: t.Optional[bool] = None4950 #: 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 hooked
2 unmodified lines
55 #: 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] = []6058 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()6768 @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 line
77 The arguments passed to :meth:`as_view` are forwarded to the78 constructor of the class.79 """8076 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)8485 if cls.decorators:86 view.__name__ = name
5 unmodified lines
92 # 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 view103104105class MethodViewType(type):
38 unmodified lines
144145 app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))146 """147143 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)150151 # If the request method is HEAD and we don't have a handler for it152 # retry with GET.
5 unmodified lines
modified:src/flask/wrappers.py+20 added-9 removed
1import typing as t23from werkzeug.exceptions import BadRequest4from werkzeug.wrappers import Request as RequestBase5from werkzeug.wrappers import Response as ResponseBase67from . import json8from .globals import current_app910if t.TYPE_CHECKING:11 from werkzeug.routing import Rule121314class Request(RequestBase):15 """The request object used by default in Flask. Remembers the16 matched endpoint and view arguments.17
17 unmodified lines
35 #: :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"] = None4041 #: 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]] = None4445 #: 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] = None5051 @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 None5859 @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 None7071 @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 None7868 def _load_form_data(self):79 def _load_form_data(self) -> None:80 RequestBase._load_form_data(self)8182 # In debug mode we're replacing the files multidict with an ad-hoc83 # subclass that raises a different error for key errors.
6 unmodified lines
90 from .debughelpers import attach_enctype_error_multidict9192 attach_enctype_error_multidict(self)9383 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}")9798 raise BadRequest()
21 unmodified lines
120121 json_module = json122123 @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.126127 See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in128 Werkzeug's docs.
6 unmodified lines
modified:CHANGES.rst+1 added
72 unmodified lines
73- ``flask shell`` sets up tab and history completion like the default74 ``python`` shell if ``readline`` is installed. :issue:`3941`75- ``helpers.total_seconds()`` is deprecated. Use76 ``timedelta.total_seconds()`` instead. :pr:`3962`77- Add type hinting. :pr:`3973`.787980Version 1.1.281-------------
1011 unmodified lines