Split the App and Blueprint into Sansio and IO parts (#5127)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by GitHub · parents 0e0e8dd, bc5dd38 · Browse files · 14 files·+2617 added−2334 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
14 files+2617 added−2334 removed
- other:+2617 added−2334 removed
Provenance
- Commit
1d8b53f- Tree
4cc2b76- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
0e0e8dd- Parent 2
bc5dd38
14 files changed+2617 added−2334 removed
modified:src/flask/json/provider.py+2 added-2 removed
9 unmodified lines10 11 from werkzeug.http import http_date12 13 if t.TYPE_CHECKING: # pragma: no cover14- from ..app import Flask14+ from ..sansio.app import App15 from ..wrappers import Response16 17 18 class JSONProvider:14 unmodified lines33 34 .. versionadded:: 2.235 """36 37- def __init__(self, app: Flask) -> None:37+ def __init__(self, app: App) -> None:38 self._app = weakref.proxy(app)39 40 def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:41 """Serialize data as JSON.175 unmodified linesadded:src/flask/sansio/app.py+964 added
1+from __future__ import annotations2+3+import logging4+import os5+import sys6+import typing as t7+from datetime import timedelta8+from itertools import chain9+10+from werkzeug.exceptions import Aborter11+from werkzeug.exceptions import BadRequest12+from werkzeug.exceptions import BadRequestKeyError13+from werkzeug.routing import BuildError14+from werkzeug.routing import Map15+from werkzeug.routing import Rule16+from werkzeug.sansio.response import Response17+from werkzeug.utils import cached_property18+from werkzeug.utils import redirect as _wz_redirect19+20+from .. import typing as ft21+from ..config import Config22+from ..config import ConfigAttribute23+from ..ctx import _AppCtxGlobals24+from ..helpers import _split_blueprint_path25+from ..helpers import get_debug_flag26+from ..json.provider import DefaultJSONProvider27+from ..json.provider import JSONProvider28+from ..logging import create_logger29+from ..templating import DispatchingJinjaLoader30+from ..templating import Environment31+from .scaffold import _endpoint_from_view_func32+from .scaffold import find_package33+from .scaffold import Scaffold34+from .scaffold import setupmethod35+36+if t.TYPE_CHECKING: # pragma: no cover37+ from werkzeug.wrappers import Response as BaseResponse38+ from .blueprints import Blueprint39+ from ..testing import FlaskClient40+ from ..testing import FlaskCliRunner41+42+T_shell_context_processor = t.TypeVar(43+ "T_shell_context_processor", bound=ft.ShellContextProcessorCallable44+)45+T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)46+T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable)47+T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable)48+T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable)49+50+51+def _make_timedelta(value: timedelta | int | None) -> timedelta | None:52+ if value is None or isinstance(value, timedelta):53+ return value54+55+ return timedelta(seconds=value)56+57+58+class App(Scaffold):59+ """The flask object implements a WSGI application and acts as the central60+ object. It is passed the name of the module or package of the61+ application. Once it is created it will act as a central registry for62+ the view functions, the URL rules, template configuration and much more.63+64+ The name of the package is used to resolve resources from inside the65+ package or the folder the module is contained in depending on if the66+ package parameter resolves to an actual python package (a folder with67+ an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).68+69+ For more information about resource loading, see :func:`open_resource`.70+71+ Usually you create a :class:`Flask` instance in your main module or72+ in the :file:`__init__.py` file of your package like this::73+74+ from flask import Flask75+ app = Flask(__name__)76+77+ .. admonition:: About the First Parameter78+79+ The idea of the first parameter is to give Flask an idea of what80+ belongs to your application. This name is used to find resources81+ on the filesystem, can be used by extensions to improve debugging82+ information and a lot more.83+84+ So it's important what you provide there. If you are using a single85+ module, `__name__` is always the correct value. If you however are86+ using a package, it's usually recommended to hardcode the name of87+ your package there.88+89+ For example if your application is defined in :file:`yourapplication/app.py`90+ you should create it with one of the two versions below::91+92+ app = Flask('yourapplication')93+ app = Flask(__name__.split('.')[0])94+95+ Why is that? The application will work even with `__name__`, thanks96+ to how resources are looked up. However it will make debugging more97+ painful. Certain extensions can make assumptions based on the98+ import name of your application. For example the Flask-SQLAlchemy99+ extension will look for the code in your application that triggered100+ an SQL query in debug mode. If the import name is not properly set101+ up, that debugging information is lost. (For example it would only102+ pick up SQL queries in `yourapplication.app` and not103+ `yourapplication.views.frontend`)104+105+ .. versionadded:: 0.7106+ The `static_url_path`, `static_folder`, and `template_folder`107+ parameters were added.108+109+ .. versionadded:: 0.8110+ The `instance_path` and `instance_relative_config` parameters were111+ added.112+113+ .. versionadded:: 0.11114+ The `root_path` parameter was added.115+116+ .. versionadded:: 1.0117+ The ``host_matching`` and ``static_host`` parameters were added.118+119+ .. versionadded:: 1.0120+ The ``subdomain_matching`` parameter was added. Subdomain121+ matching needs to be enabled manually now. Setting122+ :data:`SERVER_NAME` does not implicitly enable it.123+124+ :param import_name: the name of the application package125+ :param static_url_path: can be used to specify a different path for the126+ static files on the web. Defaults to the name127+ of the `static_folder` folder.128+ :param static_folder: The folder with static files that is served at129+ ``static_url_path``. Relative to the application ``root_path``130+ or an absolute path. Defaults to ``'static'``.131+ :param static_host: the host to use when adding the static route.132+ Defaults to None. Required when using ``host_matching=True``133+ with a ``static_folder`` configured.134+ :param host_matching: set ``url_map.host_matching`` attribute.135+ Defaults to False.136+ :param subdomain_matching: consider the subdomain relative to137+ :data:`SERVER_NAME` when matching routes. Defaults to False.138+ :param template_folder: the folder that contains the templates that should139+ be used by the application. Defaults to140+ ``'templates'`` folder in the root path of the141+ application.142+ :param instance_path: An alternative instance path for the application.143+ By default the folder ``'instance'`` next to the144+ package or module is assumed to be the instance145+ path.146+ :param instance_relative_config: if set to ``True`` relative filenames147+ for loading the config are assumed to148+ be relative to the instance path instead149+ of the application root.150+ :param root_path: The path to the root of the application files.151+ This should only be set manually when it can't be detected152+ automatically, such as for namespace packages.153+ """154+155+ #: The class of the object assigned to :attr:`aborter`, created by156+ #: :meth:`create_aborter`. That object is called by157+ #: :func:`flask.abort` to raise HTTP errors, and can be158+ #: called directly as well.159+ #:160+ #: Defaults to :class:`werkzeug.exceptions.Aborter`.161+ #:162+ #: .. versionadded:: 2.2163+ aborter_class = Aborter164+165+ #: The class that is used for the Jinja environment.166+ #:167+ #: .. versionadded:: 0.11168+ jinja_environment = Environment169+170+ #: The class that is used for the :data:`~flask.g` instance.171+ #:172+ #: Example use cases for a custom class:173+ #:174+ #: 1. Store arbitrary attributes on flask.g.175+ #: 2. Add a property for lazy per-request database connectors.176+ #: 3. Return None instead of AttributeError on unexpected attributes.177+ #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g.178+ #:179+ #: In Flask 0.9 this property was called `request_globals_class` but it180+ #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the181+ #: flask.g object is now application context scoped.182+ #:183+ #: .. versionadded:: 0.10184+ app_ctx_globals_class = _AppCtxGlobals185+186+ #: The class that is used for the ``config`` attribute of this app.187+ #: Defaults to :class:`~flask.Config`.188+ #:189+ #: Example use cases for a custom class:190+ #:191+ #: 1. Default values for certain config options.192+ #: 2. Access to config values through attributes in addition to keys.193+ #:194+ #: .. versionadded:: 0.11195+ config_class = Config196+197+ #: The testing flag. Set this to ``True`` to enable the test mode of198+ #: Flask extensions (and in the future probably also Flask itself).199+ #: For example this might activate test helpers that have an200+ #: additional runtime cost which should not be enabled by default.201+ #:202+ #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the203+ #: default it's implicitly enabled.204+ #:205+ #: This attribute can also be configured from the config with the206+ #: ``TESTING`` configuration key. Defaults to ``False``.207+ testing = ConfigAttribute("TESTING")208+209+ #: If a secret key is set, cryptographic components can use this to210+ #: sign cookies and other things. Set this to a complex random value211+ #: when you want to use the secure cookie for instance.212+ #:213+ #: This attribute can also be configured from the config with the214+ #: :data:`SECRET_KEY` configuration key. Defaults to ``None``.215+ secret_key = ConfigAttribute("SECRET_KEY")216+217+ #: A :class:`~datetime.timedelta` which is used to set the expiration218+ #: date of a permanent session. The default is 31 days which makes a219+ #: permanent session survive for roughly one month.220+ #:221+ #: This attribute can also be configured from the config with the222+ #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to223+ #: ``timedelta(days=31)``224+ permanent_session_lifetime = ConfigAttribute(225+ "PERMANENT_SESSION_LIFETIME", get_converter=_make_timedelta226+ )227+228+ json_provider_class: type[JSONProvider] = DefaultJSONProvider229+ """A subclass of :class:`~flask.json.provider.JSONProvider`. An230+ instance is created and assigned to :attr:`app.json` when creating231+ the app.232+233+ The default, :class:`~flask.json.provider.DefaultJSONProvider`, uses234+ Python's built-in :mod:`json` library. A different provider can use235+ a different JSON library.236+237+ .. versionadded:: 2.2238+ """239+240+ #: Options that are passed to the Jinja environment in241+ #: :meth:`create_jinja_environment`. Changing these options after242+ #: the environment is created (accessing :attr:`jinja_env`) will243+ #: have no effect.244+ #:245+ #: .. versionchanged:: 1.1.0246+ #: This is a ``dict`` instead of an ``ImmutableDict`` to allow247+ #: easier configuration.248+ #:249+ jinja_options: dict = {}250+251+ #: The rule object to use for URL rules created. This is used by252+ #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.253+ #:254+ #: .. versionadded:: 0.7255+ url_rule_class = Rule256+257+ #: The map object to use for storing the URL rules and routing258+ #: configuration parameters. Defaults to :class:`werkzeug.routing.Map`.259+ #:260+ #: .. versionadded:: 1.1.0261+ url_map_class = Map262+263+ #: The :meth:`test_client` method creates an instance of this test264+ #: client class. Defaults to :class:`~flask.testing.FlaskClient`.265+ #:266+ #: .. versionadded:: 0.7267+ test_client_class: type[FlaskClient] | None = None268+269+ #: The :class:`~click.testing.CliRunner` subclass, by default270+ #: :class:`~flask.testing.FlaskCliRunner` that is used by271+ #: :meth:`test_cli_runner`. Its ``__init__`` method should take a272+ #: Flask app object as the first argument.273+ #:274+ #: .. versionadded:: 1.0275+ test_cli_runner_class: type[FlaskCliRunner] | None = None276+277+ default_config: dict278+ response_class: type[Response]279+280+ def __init__(281+ self,282+ import_name: str,283+ static_url_path: str | None = None,284+ static_folder: str | os.PathLike | None = "static",285+ static_host: str | None = None,286+ host_matching: bool = False,287+ subdomain_matching: bool = False,288+ template_folder: str | os.PathLike | None = "templates",289+ instance_path: str | None = None,290+ instance_relative_config: bool = False,291+ root_path: str | None = None,292+ ):293+ super().__init__(294+ import_name=import_name,295+ static_folder=static_folder,296+ static_url_path=static_url_path,297+ template_folder=template_folder,298+ root_path=root_path,299+ )300+301+ if instance_path is None:302+ instance_path = self.auto_find_instance_path()303+ elif not os.path.isabs(instance_path):304+ raise ValueError(305+ "If an instance path is provided it must be absolute."306+ " A relative path was given instead."307+ )308+309+ #: Holds the path to the instance folder.310+ #:311+ #: .. versionadded:: 0.8312+ self.instance_path = instance_path313+314+ #: The configuration dictionary as :class:`Config`. This behaves315+ #: exactly like a regular dictionary but supports additional methods316+ #: to load a config from files.317+ self.config = self.make_config(instance_relative_config)318+319+ #: An instance of :attr:`aborter_class` created by320+ #: :meth:`make_aborter`. This is called by :func:`flask.abort`321+ #: to raise HTTP errors, and can be called directly as well.322+ #:323+ #: .. versionadded:: 2.2324+ #: Moved from ``flask.abort``, which calls this object.325+ self.aborter = self.make_aborter()326+327+ self.json: JSONProvider = self.json_provider_class(self)328+ """Provides access to JSON methods. Functions in ``flask.json``329+ will call methods on this provider when the application context330+ is active. Used for handling JSON requests and responses.331+332+ An instance of :attr:`json_provider_class`. Can be customized by333+ changing that attribute on a subclass, or by assigning to this334+ attribute afterwards.335+336+ The default, :class:`~flask.json.provider.DefaultJSONProvider`,337+ uses Python's built-in :mod:`json` library. A different provider338+ can use a different JSON library.339+340+ .. versionadded:: 2.2341+ """342+343+ #: A list of functions that are called by344+ #: :meth:`handle_url_build_error` when :meth:`.url_for` raises a345+ #: :exc:`~werkzeug.routing.BuildError`. Each function is called346+ #: with ``error``, ``endpoint`` and ``values``. If a function347+ #: returns ``None`` or raises a ``BuildError``, it is skipped.348+ #: Otherwise, its return value is returned by ``url_for``.349+ #:350+ #: .. versionadded:: 0.9351+ self.url_build_error_handlers: list[352+ t.Callable[[Exception, str, dict[str, t.Any]], str]353+ ] = []354+355+ #: A list of functions that are called when the application context356+ #: is destroyed. Since the application context is also torn down357+ #: if the request ends this is the place to store code that disconnects358+ #: from databases.359+ #:360+ #: .. versionadded:: 0.9361+ self.teardown_appcontext_funcs: list[ft.TeardownCallable] = []362+363+ #: A list of shell context processor functions that should be run364+ #: when a shell context is created.365+ #:366+ #: .. versionadded:: 0.11367+ self.shell_context_processors: list[ft.ShellContextProcessorCallable] = []368+369+ #: Maps registered blueprint names to blueprint objects. The370+ #: dict retains the order the blueprints were registered in.371+ #: Blueprints can be registered multiple times, this dict does372+ #: not track how often they were attached.373+ #:374+ #: .. versionadded:: 0.7375+ self.blueprints: dict[str, Blueprint] = {}376+377+ #: a place where extensions can store application specific state. For378+ #: example this is where an extension could store database engines and379+ #: similar things.380+ #:381+ #: The key must match the name of the extension module. For example in382+ #: case of a "Flask-Foo" extension in `flask_foo`, the key would be383+ #: ``'foo'``.384+ #:385+ #: .. versionadded:: 0.7386+ self.extensions: dict = {}387+388+ #: The :class:`~werkzeug.routing.Map` for this instance. You can use389+ #: this to change the routing converters after the class was created390+ #: but before any routes are connected. Example::391+ #:392+ #: from werkzeug.routing import BaseConverter393+ #:394+ #: class ListConverter(BaseConverter):395+ #: def to_python(self, value):396+ #: return value.split(',')397+ #: def to_url(self, values):398+ #: return ','.join(super(ListConverter, self).to_url(value)399+ #: for value in values)400+ #:401+ #: app = Flask(__name__)402+ #: app.url_map.converters['list'] = ListConverter403+ self.url_map = self.url_map_class(host_matching=host_matching)404+405+ self.subdomain_matching = subdomain_matching406+407+ # tracks internally if the application already handled at least one408+ # request.409+ self._got_first_request = False410+411+ # Set the name of the Click group in case someone wants to add412+ # the app's commands to another CLI tool.413+ self.cli.name = self.name414+415+ def _check_setup_finished(self, f_name: str) -> None:416+ if self._got_first_request:417+ raise AssertionError(418+ f"The setup method '{f_name}' can no longer be called"419+ " on the application. It has already handled its first"420+ " request, any changes will not be applied"421+ " consistently.\n"422+ "Make sure all imports, decorators, functions, etc."423+ " needed to set up the application are done before"424+ " running it."425+ )426+427+ @cached_property428+ def name(self) -> str: # type: ignore429+ """The name of the application. This is usually the import name430+ with the difference that it's guessed from the run file if the431+ import name is main. This name is used as a display name when432+ Flask needs the name of the application. It can be set and overridden433+ to change the value.434+435+ .. versionadded:: 0.8436+ """437+ if self.import_name == "__main__":438+ fn = getattr(sys.modules["__main__"], "__file__", None)439+ if fn is None:440+ return "__main__"441+ return os.path.splitext(os.path.basename(fn))[0]442+ return self.import_name443+444+ @cached_property445+ def logger(self) -> logging.Logger:446+ """A standard Python :class:`~logging.Logger` for the app, with447+ the same name as :attr:`name`.448+449+ In debug mode, the logger's :attr:`~logging.Logger.level` will450+ be set to :data:`~logging.DEBUG`.451+452+ If there are no handlers configured, a default handler will be453+ added. See :doc:`/logging` for more information.454+455+ .. versionchanged:: 1.1.0456+ The logger takes the same name as :attr:`name` rather than457+ hard-coding ``"flask.app"``.458+459+ .. versionchanged:: 1.0.0460+ Behavior was simplified. The logger is always named461+ ``"flask.app"``. The level is only set during configuration,462+ it doesn't check ``app.debug`` each time. Only one format is463+ used, not different ones depending on ``app.debug``. No464+ handlers are removed, and a handler is only added if no465+ handlers are already configured.466+467+ .. versionadded:: 0.3468+ """469+ return create_logger(self)470+471+ @cached_property472+ def jinja_env(self) -> Environment:473+ """The Jinja environment used to load templates.474+475+ The environment is created the first time this property is476+ accessed. Changing :attr:`jinja_options` after that will have no477+ effect.478+ """479+ return self.create_jinja_environment()480+481+ def create_jinja_environment(self) -> Environment:482+ raise NotImplementedError()483+484+ def make_config(self, instance_relative: bool = False) -> Config:485+ """Used to create the config attribute by the Flask constructor.486+ The `instance_relative` parameter is passed in from the constructor487+ of Flask (there named `instance_relative_config`) and indicates if488+ the config should be relative to the instance path or the root path489+ of the application.490+491+ .. versionadded:: 0.8492+ """493+ root_path = self.root_path494+ if instance_relative:495+ root_path = self.instance_path496+ defaults = dict(self.default_config)497+ defaults["DEBUG"] = get_debug_flag()498+ return self.config_class(root_path, defaults)499+500+ def make_aborter(self) -> Aborter:501+ """Create the object to assign to :attr:`aborter`. That object502+ is called by :func:`flask.abort` to raise HTTP errors, and can503+ be called directly as well.504+505+ By default, this creates an instance of :attr:`aborter_class`,506+ which defaults to :class:`werkzeug.exceptions.Aborter`.507+508+ .. versionadded:: 2.2509+ """510+ return self.aborter_class()511+512+ def auto_find_instance_path(self) -> str:513+ """Tries to locate the instance path if it was not provided to the514+ constructor of the application class. It will basically calculate515+ the path to a folder named ``instance`` next to your main file or516+ the package.517+518+ .. versionadded:: 0.8519+ """520+ prefix, package_path = find_package(self.import_name)521+ if prefix is None:522+ return os.path.join(package_path, "instance")523+ return os.path.join(prefix, "var", f"{self.name}-instance")524+525+ def create_global_jinja_loader(self) -> DispatchingJinjaLoader:526+ """Creates the loader for the Jinja2 environment. Can be used to527+ override just the loader and keeping the rest unchanged. It's528+ discouraged to override this function. Instead one should override529+ the :meth:`jinja_loader` function instead.530+531+ The global loader dispatches between the loaders of the application532+ and the individual blueprints.533+534+ .. versionadded:: 0.7535+ """536+ return DispatchingJinjaLoader(self)537+538+ def select_jinja_autoescape(self, filename: str) -> bool:539+ """Returns ``True`` if autoescaping should be active for the given540+ template name. If no template name is given, returns `True`.541+542+ .. versionchanged:: 2.2543+ Autoescaping is now enabled by default for ``.svg`` files.544+545+ .. versionadded:: 0.5546+ """547+ if filename is None:548+ return True549+ return filename.endswith((".html", ".htm", ".xml", ".xhtml", ".svg"))550+551+ @property552+ def debug(self) -> bool:553+ """Whether debug mode is enabled. When using ``flask run`` to start the554+ development server, an interactive debugger will be shown for unhandled555+ exceptions, and the server will be reloaded when code changes. This maps to the556+ :data:`DEBUG` config key. It may not behave as expected if set late.557+558+ **Do not enable debug mode when deploying in production.**559+560+ Default: ``False``561+ """562+ return self.config["DEBUG"]563+564+ @debug.setter565+ def debug(self, value: bool) -> None:566+ self.config["DEBUG"] = value567+568+ if self.config["TEMPLATES_AUTO_RELOAD"] is None:569+ self.jinja_env.auto_reload = value570+571+ @setupmethod572+ def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:573+ """Register a :class:`~flask.Blueprint` on the application. Keyword574+ arguments passed to this method will override the defaults set on the575+ blueprint.576+577+ Calls the blueprint's :meth:`~flask.Blueprint.register` method after578+ recording the blueprint in the application's :attr:`blueprints`.579+580+ :param blueprint: The blueprint to register.581+ :param url_prefix: Blueprint routes will be prefixed with this.582+ :param subdomain: Blueprint routes will match on this subdomain.583+ :param url_defaults: Blueprint routes will use these default values for584+ view arguments.585+ :param options: Additional keyword arguments are passed to586+ :class:`~flask.blueprints.BlueprintSetupState`. They can be587+ accessed in :meth:`~flask.Blueprint.record` callbacks.588+589+ .. versionchanged:: 2.0.1590+ The ``name`` option can be used to change the (pre-dotted)591+ name the blueprint is registered with. This allows the same592+ blueprint to be registered multiple times with unique names593+ for ``url_for``.594+595+ .. versionadded:: 0.7596+ """597+ blueprint.register(self, options)598+599+ def iter_blueprints(self) -> t.ValuesView[Blueprint]:600+ """Iterates over all blueprints by the order they were registered.601+602+ .. versionadded:: 0.11603+ """604+ return self.blueprints.values()605+606+ @setupmethod607+ def add_url_rule(608+ self,609+ rule: str,610+ endpoint: str | None = None,611+ view_func: ft.RouteCallable | None = None,612+ provide_automatic_options: bool | None = None,613+ **options: t.Any,614+ ) -> None:615+ if endpoint is None:616+ endpoint = _endpoint_from_view_func(view_func) # type: ignore617+ options["endpoint"] = endpoint618+ methods = options.pop("methods", None)619+620+ # if the methods are not given and the view_func object knows its621+ # methods we can use that instead. If neither exists, we go with622+ # a tuple of only ``GET`` as default.623+ if methods is None:624+ methods = getattr(view_func, "methods", None) or ("GET",)625+ if isinstance(methods, str):626+ raise TypeError(627+ "Allowed methods must be a list of strings, for"628+ ' example: @app.route(..., methods=["POST"])'629+ )630+ methods = {item.upper() for item in methods}631+632+ # Methods that should always be added633+ required_methods = set(getattr(view_func, "required_methods", ()))634+635+ # starting with Flask 0.8 the view_func object can disable and636+ # force-enable the automatic options handling.637+ if provide_automatic_options is None:638+ provide_automatic_options = getattr(639+ view_func, "provide_automatic_options", None640+ )641+642+ if provide_automatic_options is None:643+ if "OPTIONS" not in methods:644+ provide_automatic_options = True645+ required_methods.add("OPTIONS")646+ else:647+ provide_automatic_options = False648+649+ # Add the required methods now.650+ methods |= required_methods651+652+ rule = self.url_rule_class(rule, methods=methods, **options)653+ rule.provide_automatic_options = provide_automatic_options # type: ignore654+655+ self.url_map.add(rule)656+ if view_func is not None:657+ old_func = self.view_functions.get(endpoint)658+ if old_func is not None and old_func != view_func:659+ raise AssertionError(660+ "View function mapping is overwriting an existing"661+ f" endpoint function: {endpoint}"662+ )663+ self.view_functions[endpoint] = view_func664+665+ @setupmethod666+ def template_filter(667+ self, name: str | None = None668+ ) -> t.Callable[[T_template_filter], T_template_filter]:669+ """A decorator that is used to register custom template filter.670+ You can specify a name for the filter, otherwise the function671+ name will be used. Example::672+673+ @app.template_filter()674+ def reverse(s):675+ return s[::-1]676+677+ :param name: the optional name of the filter, otherwise the678+ function name will be used.679+ """680+681+ def decorator(f: T_template_filter) -> T_template_filter:682+ self.add_template_filter(f, name=name)683+ return f684+685+ return decorator686+687+ @setupmethod688+ def add_template_filter(689+ self, f: ft.TemplateFilterCallable, name: str | None = None690+ ) -> None:691+ """Register a custom template filter. Works exactly like the692+ :meth:`template_filter` decorator.693+694+ :param name: the optional name of the filter, otherwise the695+ function name will be used.696+ """697+ self.jinja_env.filters[name or f.__name__] = f698+699+ @setupmethod700+ def template_test(701+ self, name: str | None = None702+ ) -> t.Callable[[T_template_test], T_template_test]:703+ """A decorator that is used to register custom template test.704+ You can specify a name for the test, otherwise the function705+ name will be used. Example::706+707+ @app.template_test()708+ def is_prime(n):709+ if n == 2:710+ return True711+ for i in range(2, int(math.ceil(math.sqrt(n))) + 1):712+ if n % i == 0:713+ return False714+ return True715+716+ .. versionadded:: 0.10717+718+ :param name: the optional name of the test, otherwise the719+ function name will be used.720+ """721+722+ def decorator(f: T_template_test) -> T_template_test:723+ self.add_template_test(f, name=name)724+ return f725+726+ return decorator727+728+ @setupmethod729+ def add_template_test(730+ self, f: ft.TemplateTestCallable, name: str | None = None731+ ) -> None:732+ """Register a custom template test. Works exactly like the733+ :meth:`template_test` decorator.734+735+ .. versionadded:: 0.10736+737+ :param name: the optional name of the test, otherwise the738+ function name will be used.739+ """740+ self.jinja_env.tests[name or f.__name__] = f741+742+ @setupmethod743+ def template_global(744+ self, name: str | None = None745+ ) -> t.Callable[[T_template_global], T_template_global]:746+ """A decorator that is used to register a custom template global function.747+ You can specify a name for the global function, otherwise the function748+ name will be used. Example::749+750+ @app.template_global()751+ def double(n):752+ return 2 * n753+754+ .. versionadded:: 0.10755+756+ :param name: the optional name of the global function, otherwise the757+ function name will be used.758+ """759+760+ def decorator(f: T_template_global) -> T_template_global:761+ self.add_template_global(f, name=name)762+ return f763+764+ return decorator765+766+ @setupmethod767+ def add_template_global(768+ self, f: ft.TemplateGlobalCallable, name: str | None = None769+ ) -> None:770+ """Register a custom template global function. Works exactly like the771+ :meth:`template_global` decorator.772+773+ .. versionadded:: 0.10774+775+ :param name: the optional name of the global function, otherwise the776+ function name will be used.777+ """778+ self.jinja_env.globals[name or f.__name__] = f779+780+ @setupmethod781+ def teardown_appcontext(self, f: T_teardown) -> T_teardown:782+ """Registers a function to be called when the application783+ context is popped. The application context is typically popped784+ after the request context for each request, at the end of CLI785+ commands, or after a manually pushed context ends.786+787+ .. code-block:: python788+789+ with app.app_context():790+ ...791+792+ When the ``with`` block exits (or ``ctx.pop()`` is called), the793+ teardown functions are called just before the app context is794+ made inactive. Since a request context typically also manages an795+ application context it would also be called when you pop a796+ request context.797+798+ When a teardown function was called because of an unhandled799+ exception it will be passed an error object. If an800+ :meth:`errorhandler` is registered, it will handle the exception801+ and the teardown will not receive it.802+803+ Teardown functions must avoid raising exceptions. If they804+ execute code that might fail they must surround that code with a805+ ``try``/``except`` block and log any errors.806+807+ The return values of teardown functions are ignored.808+809+ .. versionadded:: 0.9810+ """811+ self.teardown_appcontext_funcs.append(f)812+ return f813+814+ @setupmethod815+ def shell_context_processor(816+ self, f: T_shell_context_processor817+ ) -> T_shell_context_processor:818+ """Registers a shell context processor function.819+820+ .. versionadded:: 0.11821+ """822+ self.shell_context_processors.append(f)823+ return f824+825+ def _find_error_handler(826+ self, e: Exception, blueprints: list[str]827+ ) -> ft.ErrorHandlerCallable | None:828+ """Return a registered error handler for an exception in this order:829+ blueprint handler for a specific code, app handler for a specific code,830+ blueprint handler for an exception class, app handler for an exception831+ class, or ``None`` if a suitable handler is not found.832+ """833+ exc_class, code = self._get_exc_class_and_code(type(e))834+ names = (*blueprints, None)835+836+ for c in (code, None) if code is not None else (None,):837+ for name in names:838+ handler_map = self.error_handler_spec[name][c]839+840+ if not handler_map:841+ continue842+843+ for cls in exc_class.__mro__:844+ handler = handler_map.get(cls)845+846+ if handler is not None:847+ return handler848+ return None849+850+ def trap_http_exception(self, e: Exception) -> bool:851+ """Checks if an HTTP exception should be trapped or not. By default852+ this will return ``False`` for all exceptions except for a bad request853+ key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It854+ also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.855+856+ This is called for all HTTP exceptions raised by a view function.857+ If it returns ``True`` for any exception the error handler for this858+ exception is not called and it shows up as regular exception in the859+ traceback. This is helpful for debugging implicitly raised HTTP860+ exceptions.861+862+ .. versionchanged:: 1.0863+ Bad request errors are not trapped by default in debug mode.864+865+ .. versionadded:: 0.8866+ """867+ if self.config["TRAP_HTTP_EXCEPTIONS"]:868+ return True869+870+ trap_bad_request = self.config["TRAP_BAD_REQUEST_ERRORS"]871+872+ # if unset, trap key errors in debug mode873+ if (874+ trap_bad_request is None875+ and self.debug876+ and isinstance(e, BadRequestKeyError)877+ ):878+ return True879+880+ if trap_bad_request:881+ return isinstance(e, BadRequest)882+883+ return False884+885+ def should_ignore_error(self, error: BaseException | None) -> bool:886+ """This is called to figure out if an error should be ignored887+ or not as far as the teardown system is concerned. If this888+ function returns ``True`` then the teardown handlers will not be889+ passed the error.890+891+ .. versionadded:: 0.10892+ """893+ return False894+895+ def redirect(self, location: str, code: int = 302) -> BaseResponse:896+ """Create a redirect response object.897+898+ This is called by :func:`flask.redirect`, and can be called899+ directly as well.900+901+ :param location: The URL to redirect to.902+ :param code: The status code for the redirect.903+904+ .. versionadded:: 2.2905+ Moved from ``flask.redirect``, which calls this method.906+ """907+ return _wz_redirect(908+ location, code=code, Response=self.response_class # type: ignore[arg-type]909+ )910+911+ def inject_url_defaults(self, endpoint: str, values: dict) -> None:912+ """Injects the URL defaults for the given endpoint directly into913+ the values dictionary passed. This is used internally and914+ automatically called on URL building.915+916+ .. versionadded:: 0.7917+ """918+ names: t.Iterable[str | None] = (None,)919+920+ # url_for may be called outside a request context, parse the921+ # passed endpoint instead of using request.blueprints.922+ if "." in endpoint:923+ names = chain(924+ names, reversed(_split_blueprint_path(endpoint.rpartition(".")[0]))925+ )926+927+ for name in names:928+ if name in self.url_default_functions:929+ for func in self.url_default_functions[name]:930+ func(endpoint, values)931+932+ def handle_url_build_error(933+ self, error: BuildError, endpoint: str, values: dict[str, t.Any]934+ ) -> str:935+ """Called by :meth:`.url_for` if a936+ :exc:`~werkzeug.routing.BuildError` was raised. If this returns937+ a value, it will be returned by ``url_for``, otherwise the error938+ will be re-raised.939+940+ Each function in :attr:`url_build_error_handlers` is called with941+ ``error``, ``endpoint`` and ``values``. If a function returns942+ ``None`` or raises a ``BuildError``, it is skipped. Otherwise,943+ its return value is returned by ``url_for``.944+945+ :param error: The active ``BuildError`` being handled.946+ :param endpoint: The endpoint being built.947+ :param values: The keyword arguments passed to ``url_for``.948+ """949+ for handler in self.url_build_error_handlers:950+ try:951+ rv = handler(error, endpoint, values)952+ except BuildError as e:953+ # make error available outside except block954+ error = e955+ else:956+ if rv is not None:957+ return rv958+959+ # Re-raise if called with an active exception, otherwise raise960+ # the passed in exception.961+ if error is sys.exc_info()[1]:962+ raise963+964+ raise erroradded:src/flask/sansio/blueprints.py+626 added
1+from __future__ import annotations2+3+import os4+import typing as t5+from collections import defaultdict6+from functools import update_wrapper7+8+from .. import typing as ft9+from .scaffold import _endpoint_from_view_func10+from .scaffold import _sentinel11+from .scaffold import Scaffold12+from .scaffold import setupmethod13+14+if t.TYPE_CHECKING: # pragma: no cover15+ from .app import App16+17+DeferredSetupFunction = t.Callable[["BlueprintSetupState"], t.Callable]18+T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable)19+T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable)20+T_error_handler = t.TypeVar("T_error_handler", bound=ft.ErrorHandlerCallable)21+T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)22+T_template_context_processor = t.TypeVar(23+ "T_template_context_processor", bound=ft.TemplateContextProcessorCallable24+)25+T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable)26+T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable)27+T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable)28+T_url_defaults = t.TypeVar("T_url_defaults", bound=ft.URLDefaultCallable)29+T_url_value_preprocessor = t.TypeVar(30+ "T_url_value_preprocessor", bound=ft.URLValuePreprocessorCallable31+)32+33+34+class BlueprintSetupState:35+ """Temporary holder object for registering a blueprint with the36+ application. An instance of this class is created by the37+ :meth:`~flask.Blueprint.make_setup_state` method and later passed38+ to all register callback functions.39+ """40+41+ def __init__(42+ self,43+ blueprint: Blueprint,44+ app: App,45+ options: t.Any,46+ first_registration: bool,47+ ) -> None:48+ #: a reference to the current application49+ self.app = app50+51+ #: a reference to the blueprint that created this setup state.52+ self.blueprint = blueprint53+54+ #: a dictionary with all options that were passed to the55+ #: :meth:`~flask.Flask.register_blueprint` method.56+ self.options = options57+58+ #: as blueprints can be registered multiple times with the59+ #: application and not everything wants to be registered60+ #: multiple times on it, this attribute can be used to figure61+ #: out if the blueprint was registered in the past already.62+ self.first_registration = first_registration63+64+ subdomain = self.options.get("subdomain")65+ if subdomain is None:66+ subdomain = self.blueprint.subdomain67+68+ #: The subdomain that the blueprint should be active for, ``None``69+ #: otherwise.70+ self.subdomain = subdomain71+72+ url_prefix = self.options.get("url_prefix")73+ if url_prefix is None:74+ url_prefix = self.blueprint.url_prefix75+ #: The prefix that should be used for all URLs defined on the76+ #: blueprint.77+ self.url_prefix = url_prefix78+79+ self.name = self.options.get("name", blueprint.name)80+ self.name_prefix = self.options.get("name_prefix", "")81+82+ #: A dictionary with URL defaults that is added to each and every83+ #: URL that was defined with the blueprint.84+ self.url_defaults = dict(self.blueprint.url_values_defaults)85+ self.url_defaults.update(self.options.get("url_defaults", ()))86+87+ def add_url_rule(88+ self,89+ rule: str,90+ endpoint: str | None = None,91+ view_func: t.Callable | None = None,92+ **options: t.Any,93+ ) -> None:94+ """A helper method to register a rule (and optionally a view function)95+ to the application. The endpoint is automatically prefixed with the96+ blueprint's name.97+ """98+ if self.url_prefix is not None:99+ if rule:100+ rule = "/".join((self.url_prefix.rstrip("/"), rule.lstrip("/")))101+ else:102+ rule = self.url_prefix103+ options.setdefault("subdomain", self.subdomain)104+ if endpoint is None:105+ endpoint = _endpoint_from_view_func(view_func) # type: ignore106+ defaults = self.url_defaults107+ if "defaults" in options:108+ defaults = dict(defaults, **options.pop("defaults"))109+110+ self.app.add_url_rule(111+ rule,112+ f"{self.name_prefix}.{self.name}.{endpoint}".lstrip("."),113+ view_func,114+ defaults=defaults,115+ **options,116+ )117+118+119+class Blueprint(Scaffold):120+ """Represents a blueprint, a collection of routes and other121+ app-related functions that can be registered on a real application122+ later.123+124+ A blueprint is an object that allows defining application functions125+ without requiring an application object ahead of time. It uses the126+ same decorators as :class:`~flask.Flask`, but defers the need for an127+ application by recording them for later registration.128+129+ Decorating a function with a blueprint creates a deferred function130+ that is called with :class:`~flask.blueprints.BlueprintSetupState`131+ when the blueprint is registered on an application.132+133+ See :doc:`/blueprints` for more information.134+135+ :param name: The name of the blueprint. Will be prepended to each136+ endpoint name.137+ :param import_name: The name of the blueprint package, usually138+ ``__name__``. This helps locate the ``root_path`` for the139+ blueprint.140+ :param static_folder: A folder with static files that should be141+ served by the blueprint's static route. The path is relative to142+ the blueprint's root path. Blueprint static files are disabled143+ by default.144+ :param static_url_path: The url to serve static files from.145+ Defaults to ``static_folder``. If the blueprint does not have146+ a ``url_prefix``, the app's static route will take precedence,147+ and the blueprint's static files won't be accessible.148+ :param template_folder: A folder with templates that should be added149+ to the app's template search path. The path is relative to the150+ blueprint's root path. Blueprint templates are disabled by151+ default. Blueprint templates have a lower precedence than those152+ in the app's templates folder.153+ :param url_prefix: A path to prepend to all of the blueprint's URLs,154+ to make them distinct from the rest of the app's routes.155+ :param subdomain: A subdomain that blueprint routes will match on by156+ default.157+ :param url_defaults: A dict of default values that blueprint routes158+ will receive by default.159+ :param root_path: By default, the blueprint will automatically set160+ this based on ``import_name``. In certain situations this161+ automatic detection can fail, so the path can be specified162+ manually instead.163+164+ .. versionchanged:: 1.1.0165+ Blueprints have a ``cli`` group to register nested CLI commands.166+ The ``cli_group`` parameter controls the name of the group under167+ the ``flask`` command.168+169+ .. versionadded:: 0.7170+ """171+172+ _got_registered_once = False173+174+ def __init__(175+ self,176+ name: str,177+ import_name: str,178+ static_folder: str | os.PathLike | None = None,179+ static_url_path: str | None = None,180+ template_folder: str | os.PathLike | None = None,181+ url_prefix: str | None = None,182+ subdomain: str | None = None,183+ url_defaults: dict | None = None,184+ root_path: str | None = None,185+ cli_group: str | None = _sentinel, # type: ignore186+ ):187+ super().__init__(188+ import_name=import_name,189+ static_folder=static_folder,190+ static_url_path=static_url_path,191+ template_folder=template_folder,192+ root_path=root_path,193+ )194+195+ if not name:196+ raise ValueError("'name' may not be empty.")197+198+ if "." in name:199+ raise ValueError("'name' may not contain a dot '.' character.")200+201+ self.name = name202+ self.url_prefix = url_prefix203+ self.subdomain = subdomain204+ self.deferred_functions: list[DeferredSetupFunction] = []205+206+ if url_defaults is None:207+ url_defaults = {}208+209+ self.url_values_defaults = url_defaults210+ self.cli_group = cli_group211+ self._blueprints: list[tuple[Blueprint, dict]] = []212+213+ def _check_setup_finished(self, f_name: str) -> None:214+ if self._got_registered_once:215+ raise AssertionError(216+ f"The setup method '{f_name}' can no longer be called on the blueprint"217+ f" '{self.name}'. It has already been registered at least once, any"218+ " changes will not be applied consistently.\n"219+ "Make sure all imports, decorators, functions, etc. needed to set up"220+ " the blueprint are done before registering it."221+ )222+223+ @setupmethod224+ def record(self, func: t.Callable) -> None:225+ """Registers a function that is called when the blueprint is226+ registered on the application. This function is called with the227+ state as argument as returned by the :meth:`make_setup_state`228+ method.229+ """230+ self.deferred_functions.append(func)231+232+ @setupmethod233+ def record_once(self, func: t.Callable) -> None:234+ """Works like :meth:`record` but wraps the function in another235+ function that will ensure the function is only called once. If the236+ blueprint is registered a second time on the application, the237+ function passed is not called.238+ """239+240+ def wrapper(state: BlueprintSetupState) -> None:241+ if state.first_registration:242+ func(state)243+244+ self.record(update_wrapper(wrapper, func))245+246+ def make_setup_state(247+ self, app: App, options: dict, first_registration: bool = False248+ ) -> BlueprintSetupState:249+ """Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`250+ object that is later passed to the register callback functions.251+ Subclasses can override this to return a subclass of the setup state.252+ """253+ return BlueprintSetupState(self, app, options, first_registration)254+255+ @setupmethod256+ def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:257+ """Register a :class:`~flask.Blueprint` on this blueprint. Keyword258+ arguments passed to this method will override the defaults set259+ on the blueprint.260+261+ .. versionchanged:: 2.0.1262+ The ``name`` option can be used to change the (pre-dotted)263+ name the blueprint is registered with. This allows the same264+ blueprint to be registered multiple times with unique names265+ for ``url_for``.266+267+ .. versionadded:: 2.0268+ """269+ if blueprint is self:270+ raise ValueError("Cannot register a blueprint on itself")271+ self._blueprints.append((blueprint, options))272+273+ def register(self, app: App, options: dict) -> None:274+ """Called by :meth:`Flask.register_blueprint` to register all275+ views and callbacks registered on the blueprint with the276+ application. Creates a :class:`.BlueprintSetupState` and calls277+ each :meth:`record` callback with it.278+279+ :param app: The application this blueprint is being registered280+ with.281+ :param options: Keyword arguments forwarded from282+ :meth:`~Flask.register_blueprint`.283+284+ .. versionchanged:: 2.3285+ Nested blueprints now correctly apply subdomains.286+287+ .. versionchanged:: 2.1288+ Registering the same blueprint with the same name multiple289+ times is an error.290+291+ .. versionchanged:: 2.0.1292+ Nested blueprints are registered with their dotted name.293+ This allows different blueprints with the same name to be294+ nested at different locations.295+296+ .. versionchanged:: 2.0.1297+ The ``name`` option can be used to change the (pre-dotted)298+ name the blueprint is registered with. This allows the same299+ blueprint to be registered multiple times with unique names300+ for ``url_for``.301+ """302+ name_prefix = options.get("name_prefix", "")303+ self_name = options.get("name", self.name)304+ name = f"{name_prefix}.{self_name}".lstrip(".")305+306+ if name in app.blueprints:307+ bp_desc = "this" if app.blueprints[name] is self else "a different"308+ existing_at = f" '{name}'" if self_name != name else ""309+310+ raise ValueError(311+ f"The name '{self_name}' is already registered for"312+ f" {bp_desc} blueprint{existing_at}. Use 'name=' to"313+ f" provide a unique name."314+ )315+316+ first_bp_registration = not any(bp is self for bp in app.blueprints.values())317+ first_name_registration = name not in app.blueprints318+319+ app.blueprints[name] = self320+ self._got_registered_once = True321+ state = self.make_setup_state(app, options, first_bp_registration)322+323+ if self.has_static_folder:324+ state.add_url_rule(325+ f"{self.static_url_path}/<path:filename>",326+ view_func=self.send_static_file, # type: ignore[attr-defined]327+ endpoint="static",328+ )329+330+ # Merge blueprint data into parent.331+ if first_bp_registration or first_name_registration:332+ self._merge_blueprint_funcs(app, name)333+334+ for deferred in self.deferred_functions:335+ deferred(state)336+337+ cli_resolved_group = options.get("cli_group", self.cli_group)338+339+ if self.cli.commands:340+ if cli_resolved_group is None:341+ app.cli.commands.update(self.cli.commands)342+ elif cli_resolved_group is _sentinel:343+ self.cli.name = name344+ app.cli.add_command(self.cli)345+ else:346+ self.cli.name = cli_resolved_group347+ app.cli.add_command(self.cli)348+349+ for blueprint, bp_options in self._blueprints:350+ bp_options = bp_options.copy()351+ bp_url_prefix = bp_options.get("url_prefix")352+ bp_subdomain = bp_options.get("subdomain")353+354+ if bp_subdomain is None:355+ bp_subdomain = blueprint.subdomain356+357+ if state.subdomain is not None and bp_subdomain is not None:358+ bp_options["subdomain"] = bp_subdomain + "." + state.subdomain359+ elif bp_subdomain is not None:360+ bp_options["subdomain"] = bp_subdomain361+ elif state.subdomain is not None:362+ bp_options["subdomain"] = state.subdomain363+364+ if bp_url_prefix is None:365+ bp_url_prefix = blueprint.url_prefix366+367+ if state.url_prefix is not None and bp_url_prefix is not None:368+ bp_options["url_prefix"] = (369+ state.url_prefix.rstrip("/") + "/" + bp_url_prefix.lstrip("/")370+ )371+ elif bp_url_prefix is not None:372+ bp_options["url_prefix"] = bp_url_prefix373+ elif state.url_prefix is not None:374+ bp_options["url_prefix"] = state.url_prefix375+376+ bp_options["name_prefix"] = name377+ blueprint.register(app, bp_options)378+379+ def _merge_blueprint_funcs(self, app: App, name: str) -> None:380+ def extend(bp_dict, parent_dict):381+ for key, values in bp_dict.items():382+ key = name if key is None else f"{name}.{key}"383+ parent_dict[key].extend(values)384+385+ for key, value in self.error_handler_spec.items():386+ key = name if key is None else f"{name}.{key}"387+ value = defaultdict(388+ dict,389+ {390+ code: {exc_class: func for exc_class, func in code_values.items()}391+ for code, code_values in value.items()392+ },393+ )394+ app.error_handler_spec[key] = value395+396+ for endpoint, func in self.view_functions.items():397+ app.view_functions[endpoint] = func398+399+ extend(self.before_request_funcs, app.before_request_funcs)400+ extend(self.after_request_funcs, app.after_request_funcs)401+ extend(402+ self.teardown_request_funcs,403+ app.teardown_request_funcs,404+ )405+ extend(self.url_default_functions, app.url_default_functions)406+ extend(self.url_value_preprocessors, app.url_value_preprocessors)407+ extend(self.template_context_processors, app.template_context_processors)408+409+ @setupmethod410+ def add_url_rule(411+ self,412+ rule: str,413+ endpoint: str | None = None,414+ view_func: ft.RouteCallable | None = None,415+ provide_automatic_options: bool | None = None,416+ **options: t.Any,417+ ) -> None:418+ """Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for419+ full documentation.420+421+ The URL rule is prefixed with the blueprint's URL prefix. The endpoint name,422+ used with :func:`url_for`, is prefixed with the blueprint's name.423+ """424+ if endpoint and "." in endpoint:425+ raise ValueError("'endpoint' may not contain a dot '.' character.")426+427+ if view_func and hasattr(view_func, "__name__") and "." in view_func.__name__:428+ raise ValueError("'view_func' name may not contain a dot '.' character.")429+430+ self.record(431+ lambda s: s.add_url_rule(432+ rule,433+ endpoint,434+ view_func,435+ provide_automatic_options=provide_automatic_options,436+ **options,437+ )438+ )439+440+ @setupmethod441+ def app_template_filter(442+ self, name: str | None = None443+ ) -> t.Callable[[T_template_filter], T_template_filter]:444+ """Register a template filter, available in any template rendered by the445+ application. Equivalent to :meth:`.Flask.template_filter`.446+447+ :param name: the optional name of the filter, otherwise the448+ function name will be used.449+ """450+451+ def decorator(f: T_template_filter) -> T_template_filter:452+ self.add_app_template_filter(f, name=name)453+ return f454+455+ return decorator456+457+ @setupmethod458+ def add_app_template_filter(459+ self, f: ft.TemplateFilterCallable, name: str | None = None460+ ) -> None:461+ """Register a template filter, available in any template rendered by the462+ application. Works like the :meth:`app_template_filter` decorator. Equivalent to463+ :meth:`.Flask.add_template_filter`.464+465+ :param name: the optional name of the filter, otherwise the466+ function name will be used.467+ """468+469+ def register_template(state: BlueprintSetupState) -> None:470+ state.app.jinja_env.filters[name or f.__name__] = f471+472+ self.record_once(register_template)473+474+ @setupmethod475+ def app_template_test(476+ self, name: str | None = None477+ ) -> t.Callable[[T_template_test], T_template_test]:478+ """Register a template test, available in any template rendered by the479+ application. Equivalent to :meth:`.Flask.template_test`.480+481+ .. versionadded:: 0.10482+483+ :param name: the optional name of the test, otherwise the484+ function name will be used.485+ """486+487+ def decorator(f: T_template_test) -> T_template_test:488+ self.add_app_template_test(f, name=name)489+ return f490+491+ return decorator492+493+ @setupmethod494+ def add_app_template_test(495+ self, f: ft.TemplateTestCallable, name: str | None = None496+ ) -> None:497+ """Register a template test, available in any template rendered by the498+ application. Works like the :meth:`app_template_test` decorator. Equivalent to499+ :meth:`.Flask.add_template_test`.500+501+ .. versionadded:: 0.10502+503+ :param name: the optional name of the test, otherwise the504+ function name will be used.505+ """506+507+ def register_template(state: BlueprintSetupState) -> None:508+ state.app.jinja_env.tests[name or f.__name__] = f509+510+ self.record_once(register_template)511+512+ @setupmethod513+ def app_template_global(514+ self, name: str | None = None515+ ) -> t.Callable[[T_template_global], T_template_global]:516+ """Register a template global, available in any template rendered by the517+ application. Equivalent to :meth:`.Flask.template_global`.518+519+ .. versionadded:: 0.10520+521+ :param name: the optional name of the global, otherwise the522+ function name will be used.523+ """524+525+ def decorator(f: T_template_global) -> T_template_global:526+ self.add_app_template_global(f, name=name)527+ return f528+529+ return decorator530+531+ @setupmethod532+ def add_app_template_global(533+ self, f: ft.TemplateGlobalCallable, name: str | None = None534+ ) -> None:535+ """Register a template global, available in any template rendered by the536+ application. Works like the :meth:`app_template_global` decorator. Equivalent to537+ :meth:`.Flask.add_template_global`.538+539+ .. versionadded:: 0.10540+541+ :param name: the optional name of the global, otherwise the542+ function name will be used.543+ """544+545+ def register_template(state: BlueprintSetupState) -> None:546+ state.app.jinja_env.globals[name or f.__name__] = f547+548+ self.record_once(register_template)549+550+ @setupmethod551+ def before_app_request(self, f: T_before_request) -> T_before_request:552+ """Like :meth:`before_request`, but before every request, not only those handled553+ by the blueprint. Equivalent to :meth:`.Flask.before_request`.554+ """555+ self.record_once(556+ lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)557+ )558+ return f559+560+ @setupmethod561+ def after_app_request(self, f: T_after_request) -> T_after_request:562+ """Like :meth:`after_request`, but after every request, not only those handled563+ by the blueprint. Equivalent to :meth:`.Flask.after_request`.564+ """565+ self.record_once(566+ lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)567+ )568+ return f569+570+ @setupmethod571+ def teardown_app_request(self, f: T_teardown) -> T_teardown:572+ """Like :meth:`teardown_request`, but after every request, not only those573+ handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`.574+ """575+ self.record_once(576+ lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)577+ )578+ return f579+580+ @setupmethod581+ def app_context_processor(582+ self, f: T_template_context_processor583+ ) -> T_template_context_processor:584+ """Like :meth:`context_processor`, but for templates rendered by every view, not585+ only by the blueprint. Equivalent to :meth:`.Flask.context_processor`.586+ """587+ self.record_once(588+ lambda s: s.app.template_context_processors.setdefault(None, []).append(f)589+ )590+ return f591+592+ @setupmethod593+ def app_errorhandler(594+ self, code: type[Exception] | int595+ ) -> t.Callable[[T_error_handler], T_error_handler]:596+ """Like :meth:`errorhandler`, but for every request, not only those handled by597+ the blueprint. Equivalent to :meth:`.Flask.errorhandler`.598+ """599+600+ def decorator(f: T_error_handler) -> T_error_handler:601+ self.record_once(lambda s: s.app.errorhandler(code)(f))602+ return f603+604+ return decorator605+606+ @setupmethod607+ def app_url_value_preprocessor(608+ self, f: T_url_value_preprocessor609+ ) -> T_url_value_preprocessor:610+ """Like :meth:`url_value_preprocessor`, but for every request, not only those611+ handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`.612+ """613+ self.record_once(614+ lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)615+ )616+ return f617+618+ @setupmethod619+ def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults:620+ """Like :meth:`url_defaults`, but for every request, not only those handled by621+ the blueprint. Equivalent to :meth:`.Flask.url_defaults`.622+ """623+ self.record_once(624+ lambda s: s.app.url_default_functions.setdefault(None, []).append(f)625+ )626+ return fadded:src/flask/sansio/README.md+6 added
123456# Sansio
This folder contains code that can be used by alternative Flaskimplementations, for example Quart. The code therefore cannot do anyIO, nor be part of a likely IO path. Finally this code cannot use theFlask globals.added:src/flask/sansio/scaffold.py+802 added
1+from __future__ import annotations2+3+import importlib.util4+import os5+import pathlib6+import sys7+import typing as t8+from collections import defaultdict9+from functools import update_wrapper10+11+from jinja2 import FileSystemLoader12+from werkzeug.exceptions import default_exceptions13+from werkzeug.exceptions import HTTPException14+from werkzeug.utils import cached_property15+16+from .. import typing as ft17+from ..cli import AppGroup18+from ..helpers import get_root_path19+from ..templating import _default_template_ctx_processor20+21+# a singleton sentinel value for parameter defaults22+_sentinel = object()23+24+F = t.TypeVar("F", bound=t.Callable[..., t.Any])25+T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable)26+T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable)27+T_error_handler = t.TypeVar("T_error_handler", bound=ft.ErrorHandlerCallable)28+T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)29+T_template_context_processor = t.TypeVar(30+ "T_template_context_processor", bound=ft.TemplateContextProcessorCallable31+)32+T_url_defaults = t.TypeVar("T_url_defaults", bound=ft.URLDefaultCallable)33+T_url_value_preprocessor = t.TypeVar(34+ "T_url_value_preprocessor", bound=ft.URLValuePreprocessorCallable35+)36+T_route = t.TypeVar("T_route", bound=ft.RouteCallable)37+38+39+def setupmethod(f: F) -> F:40+ f_name = f.__name__41+42+ def wrapper_func(self, *args: t.Any, **kwargs: t.Any) -> t.Any:43+ self._check_setup_finished(f_name)44+ return f(self, *args, **kwargs)45+46+ return t.cast(F, update_wrapper(wrapper_func, f))47+48+49+class Scaffold:50+ """Common behavior shared between :class:`~flask.Flask` and51+ :class:`~flask.blueprints.Blueprint`.52+53+ :param import_name: The import name of the module where this object54+ is defined. Usually :attr:`__name__` should be used.55+ :param static_folder: Path to a folder of static files to serve.56+ If this is set, a static route will be added.57+ :param static_url_path: URL prefix for the static route.58+ :param template_folder: Path to a folder containing template files.59+ for rendering. If this is set, a Jinja loader will be added.60+ :param root_path: The path that static, template, and resource files61+ are relative to. Typically not set, it is discovered based on62+ the ``import_name``.63+64+ .. versionadded:: 2.065+ """66+67+ name: str68+ _static_folder: str | None = None69+ _static_url_path: str | None = None70+71+ def __init__(72+ self,73+ import_name: str,74+ static_folder: str | os.PathLike | None = None,75+ static_url_path: str | None = None,76+ template_folder: str | os.PathLike | None = None,77+ root_path: str | None = None,78+ ):79+ #: The name of the package or module that this object belongs80+ #: to. Do not change this once it is set by the constructor.81+ self.import_name = import_name82+83+ self.static_folder = static_folder # type: ignore84+ self.static_url_path = static_url_path85+86+ #: The path to the templates folder, relative to87+ #: :attr:`root_path`, to add to the template loader. ``None`` if88+ #: templates should not be added.89+ self.template_folder = template_folder90+91+ if root_path is None:92+ root_path = get_root_path(self.import_name)93+94+ #: Absolute path to the package on the filesystem. Used to look95+ #: up resources contained in the package.96+ self.root_path = root_path97+98+ #: The Click command group for registering CLI commands for this99+ #: object. The commands are available from the ``flask`` command100+ #: once the application has been discovered and blueprints have101+ #: been registered.102+ self.cli = AppGroup()103+104+ #: A dictionary mapping endpoint names to view functions.105+ #:106+ #: To register a view function, use the :meth:`route` decorator.107+ #:108+ #: This data structure is internal. It should not be modified109+ #: directly and its format may change at any time.110+ self.view_functions: dict[str, t.Callable] = {}111+112+ #: A data structure of registered error handlers, in the format113+ #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is114+ #: the name of a blueprint the handlers are active for, or115+ #: ``None`` for all requests. The ``code`` key is the HTTP116+ #: status code for ``HTTPException``, or ``None`` for117+ #: other exceptions. The innermost dictionary maps exception118+ #: classes to handler functions.119+ #:120+ #: To register an error handler, use the :meth:`errorhandler`121+ #: decorator.122+ #:123+ #: This data structure is internal. It should not be modified124+ #: directly and its format may change at any time.125+ self.error_handler_spec: dict[126+ ft.AppOrBlueprintKey,127+ dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]],128+ ] = defaultdict(lambda: defaultdict(dict))129+130+ #: A data structure of functions to call at the beginning of131+ #: each request, in the format ``{scope: [functions]}``. The132+ #: ``scope`` key is the name of a blueprint the functions are133+ #: active for, or ``None`` for all requests.134+ #:135+ #: To register a function, use the :meth:`before_request`136+ #: decorator.137+ #:138+ #: This data structure is internal. It should not be modified139+ #: directly and its format may change at any time.140+ self.before_request_funcs: dict[141+ ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]142+ ] = defaultdict(list)143+144+ #: A data structure of functions to call at the end of each145+ #: request, in the format ``{scope: [functions]}``. The146+ #: ``scope`` key is the name of a blueprint the functions are147+ #: active for, or ``None`` for all requests.148+ #:149+ #: To register a function, use the :meth:`after_request`150+ #: decorator.151+ #:152+ #: This data structure is internal. It should not be modified153+ #: directly and its format may change at any time.154+ self.after_request_funcs: dict[155+ ft.AppOrBlueprintKey, list[ft.AfterRequestCallable]156+ ] = defaultdict(list)157+158+ #: A data structure of functions to call at the end of each159+ #: request even if an exception is raised, in the format160+ #: ``{scope: [functions]}``. The ``scope`` key is the name of a161+ #: blueprint the functions are active for, or ``None`` for all162+ #: requests.163+ #:164+ #: To register a function, use the :meth:`teardown_request`165+ #: decorator.166+ #:167+ #: This data structure is internal. It should not be modified168+ #: directly and its format may change at any time.169+ self.teardown_request_funcs: dict[170+ ft.AppOrBlueprintKey, list[ft.TeardownCallable]171+ ] = defaultdict(list)172+173+ #: A data structure of functions to call to pass extra context174+ #: values when rendering templates, in the format175+ #: ``{scope: [functions]}``. The ``scope`` key is the name of a176+ #: blueprint the functions are active for, or ``None`` for all177+ #: requests.178+ #:179+ #: To register a function, use the :meth:`context_processor`180+ #: decorator.181+ #:182+ #: This data structure is internal. It should not be modified183+ #: directly and its format may change at any time.184+ self.template_context_processors: dict[185+ ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]186+ ] = defaultdict(list, {None: [_default_template_ctx_processor]})187+188+ #: A data structure of functions to call to modify the keyword189+ #: arguments passed to the view function, in the format190+ #: ``{scope: [functions]}``. The ``scope`` key is the name of a191+ #: blueprint the functions are active for, or ``None`` for all192+ #: requests.193+ #:194+ #: To register a function, use the195+ #: :meth:`url_value_preprocessor` decorator.196+ #:197+ #: This data structure is internal. It should not be modified198+ #: directly and its format may change at any time.199+ self.url_value_preprocessors: dict[200+ ft.AppOrBlueprintKey,201+ list[ft.URLValuePreprocessorCallable],202+ ] = defaultdict(list)203+204+ #: A data structure of functions to call to modify the keyword205+ #: arguments when generating URLs, in the format206+ #: ``{scope: [functions]}``. The ``scope`` key is the name of a207+ #: blueprint the functions are active for, or ``None`` for all208+ #: requests.209+ #:210+ #: To register a function, use the :meth:`url_defaults`211+ #: decorator.212+ #:213+ #: This data structure is internal. It should not be modified214+ #: directly and its format may change at any time.215+ self.url_default_functions: dict[216+ ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]217+ ] = defaultdict(list)218+219+ def __repr__(self) -> str:220+ return f"<{type(self).__name__} {self.name!r}>"221+222+ def _check_setup_finished(self, f_name: str) -> None:223+ raise NotImplementedError224+225+ @property226+ def static_folder(self) -> str | None:227+ """The absolute path to the configured static folder. ``None``228+ if no static folder is set.229+ """230+ if self._static_folder is not None:231+ return os.path.join(self.root_path, self._static_folder)232+ else:233+ return None234+235+ @static_folder.setter236+ def static_folder(self, value: str | os.PathLike | None) -> None:237+ if value is not None:238+ value = os.fspath(value).rstrip(r"\/")239+240+ self._static_folder = value241+242+ @property243+ def has_static_folder(self) -> bool:244+ """``True`` if :attr:`static_folder` is set.245+246+ .. versionadded:: 0.5247+ """248+ return self.static_folder is not None249+250+ @property251+ def static_url_path(self) -> str | None:252+ """The URL prefix that the static route will be accessible from.253+254+ If it was not configured during init, it is derived from255+ :attr:`static_folder`.256+ """257+ if self._static_url_path is not None:258+ return self._static_url_path259+260+ if self.static_folder is not None:261+ basename = os.path.basename(self.static_folder)262+ return f"/{basename}".rstrip("/")263+264+ return None265+266+ @static_url_path.setter267+ def static_url_path(self, value: str | None) -> None:268+ if value is not None:269+ value = value.rstrip("/")270+271+ self._static_url_path = value272+273+ @cached_property274+ def jinja_loader(self) -> FileSystemLoader | None:275+ """The Jinja loader for this object's templates. By default this276+ is a class :class:`jinja2.loaders.FileSystemLoader` to277+ :attr:`template_folder` if it is set.278+279+ .. versionadded:: 0.5280+ """281+ if self.template_folder is not None:282+ return FileSystemLoader(os.path.join(self.root_path, self.template_folder))283+ else:284+ return None285+286+ def _method_route(287+ self,288+ method: str,289+ rule: str,290+ options: dict,291+ ) -> t.Callable[[T_route], T_route]:292+ if "methods" in options:293+ raise TypeError("Use the 'route' decorator to use the 'methods' argument.")294+295+ return self.route(rule, methods=[method], **options)296+297+ @setupmethod298+ def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:299+ """Shortcut for :meth:`route` with ``methods=["GET"]``.300+301+ .. versionadded:: 2.0302+ """303+ return self._method_route("GET", rule, options)304+305+ @setupmethod306+ def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:307+ """Shortcut for :meth:`route` with ``methods=["POST"]``.308+309+ .. versionadded:: 2.0310+ """311+ return self._method_route("POST", rule, options)312+313+ @setupmethod314+ def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:315+ """Shortcut for :meth:`route` with ``methods=["PUT"]``.316+317+ .. versionadded:: 2.0318+ """319+ return self._method_route("PUT", rule, options)320+321+ @setupmethod322+ def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:323+ """Shortcut for :meth:`route` with ``methods=["DELETE"]``.324+325+ .. versionadded:: 2.0326+ """327+ return self._method_route("DELETE", rule, options)328+329+ @setupmethod330+ def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:331+ """Shortcut for :meth:`route` with ``methods=["PATCH"]``.332+333+ .. versionadded:: 2.0334+ """335+ return self._method_route("PATCH", rule, options)336+337+ @setupmethod338+ def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:339+ """Decorate a view function to register it with the given URL340+ rule and options. Calls :meth:`add_url_rule`, which has more341+ details about the implementation.342+343+ .. code-block:: python344+345+ @app.route("/")346+ def index():347+ return "Hello, World!"348+349+ See :ref:`url-route-registrations`.350+351+ The endpoint name for the route defaults to the name of the view352+ function if the ``endpoint`` parameter isn't passed.353+354+ The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and355+ ``OPTIONS`` are added automatically.356+357+ :param rule: The URL rule string.358+ :param options: Extra options passed to the359+ :class:`~werkzeug.routing.Rule` object.360+ """361+362+ def decorator(f: T_route) -> T_route:363+ endpoint = options.pop("endpoint", None)364+ self.add_url_rule(rule, endpoint, f, **options)365+ return f366+367+ return decorator368+369+ @setupmethod370+ def add_url_rule(371+ self,372+ rule: str,373+ endpoint: str | None = None,374+ view_func: ft.RouteCallable | None = None,375+ provide_automatic_options: bool | None = None,376+ **options: t.Any,377+ ) -> None:378+ """Register a rule for routing incoming requests and building379+ URLs. The :meth:`route` decorator is a shortcut to call this380+ with the ``view_func`` argument. These are equivalent:381+382+ .. code-block:: python383+384+ @app.route("/")385+ def index():386+ ...387+388+ .. code-block:: python389+390+ def index():391+ ...392+393+ app.add_url_rule("/", view_func=index)394+395+ See :ref:`url-route-registrations`.396+397+ The endpoint name for the route defaults to the name of the view398+ function if the ``endpoint`` parameter isn't passed. An error399+ will be raised if a function has already been registered for the400+ endpoint.401+402+ The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` is403+ always added automatically, and ``OPTIONS`` is added404+ automatically by default.405+406+ ``view_func`` does not necessarily need to be passed, but if the407+ rule should participate in routing an endpoint name must be408+ associated with a view function at some point with the409+ :meth:`endpoint` decorator.410+411+ .. code-block:: python412+413+ app.add_url_rule("/", endpoint="index")414+415+ @app.endpoint("index")416+ def index():417+ ...418+419+ If ``view_func`` has a ``required_methods`` attribute, those420+ methods are added to the passed and automatic methods. If it421+ has a ``provide_automatic_methods`` attribute, it is used as the422+ default if the parameter is not passed.423+424+ :param rule: The URL rule string.425+ :param endpoint: The endpoint name to associate with the rule426+ and view function. Used when routing and building URLs.427+ Defaults to ``view_func.__name__``.428+ :param view_func: The view function to associate with the429+ endpoint name.430+ :param provide_automatic_options: Add the ``OPTIONS`` method and431+ respond to ``OPTIONS`` requests automatically.432+ :param options: Extra options passed to the433+ :class:`~werkzeug.routing.Rule` object.434+ """435+ raise NotImplementedError436+437+ @setupmethod438+ def endpoint(self, endpoint: str) -> t.Callable[[F], F]:439+ """Decorate a view function to register it for the given440+ endpoint. Used if a rule is added without a ``view_func`` with441+ :meth:`add_url_rule`.442+443+ .. code-block:: python444+445+ app.add_url_rule("/ex", endpoint="example")446+447+ @app.endpoint("example")448+ def example():449+ ...450+451+ :param endpoint: The endpoint name to associate with the view452+ function.453+ """454+455+ def decorator(f: F) -> F:456+ self.view_functions[endpoint] = f457+ return f458+459+ return decorator460+461+ @setupmethod462+ def before_request(self, f: T_before_request) -> T_before_request:463+ """Register a function to run before each request.464+465+ For example, this can be used to open a database connection, or466+ to load the logged in user from the session.467+468+ .. code-block:: python469+470+ @app.before_request471+ def load_user():472+ if "user_id" in session:473+ g.user = db.session.get(session["user_id"])474+475+ The function will be called without any arguments. If it returns476+ a non-``None`` value, the value is handled as if it was the477+ return value from the view, and further request handling is478+ stopped.479+480+ This is available on both app and blueprint objects. When used on an app, this481+ executes before every request. When used on a blueprint, this executes before482+ every request that the blueprint handles. To register with a blueprint and483+ execute before every request, use :meth:`.Blueprint.before_app_request`.484+ """485+ self.before_request_funcs.setdefault(None, []).append(f)486+ return f487+488+ @setupmethod489+ def after_request(self, f: T_after_request) -> T_after_request:490+ """Register a function to run after each request to this object.491+492+ The function is called with the response object, and must return493+ a response object. This allows the functions to modify or494+ replace the response before it is sent.495+496+ If a function raises an exception, any remaining497+ ``after_request`` functions will not be called. Therefore, this498+ should not be used for actions that must execute, such as to499+ close resources. Use :meth:`teardown_request` for that.500+501+ This is available on both app and blueprint objects. When used on an app, this502+ executes after every request. When used on a blueprint, this executes after503+ every request that the blueprint handles. To register with a blueprint and504+ execute after every request, use :meth:`.Blueprint.after_app_request`.505+ """506+ self.after_request_funcs.setdefault(None, []).append(f)507+ return f508+509+ @setupmethod510+ def teardown_request(self, f: T_teardown) -> T_teardown:511+ """Register a function to be called when the request context is512+ popped. Typically this happens at the end of each request, but513+ contexts may be pushed manually as well during testing.514+515+ .. code-block:: python516+517+ with app.test_request_context():518+ ...519+520+ When the ``with`` block exits (or ``ctx.pop()`` is called), the521+ teardown functions are called just before the request context is522+ made inactive.523+524+ When a teardown function was called because of an unhandled525+ exception it will be passed an error object. If an526+ :meth:`errorhandler` is registered, it will handle the exception527+ and the teardown will not receive it.528+529+ Teardown functions must avoid raising exceptions. If they530+ execute code that might fail they must surround that code with a531+ ``try``/``except`` block and log any errors.532+533+ The return values of teardown functions are ignored.534+535+ This is available on both app and blueprint objects. When used on an app, this536+ executes after every request. When used on a blueprint, this executes after537+ every request that the blueprint handles. To register with a blueprint and538+ execute after every request, use :meth:`.Blueprint.teardown_app_request`.539+ """540+ self.teardown_request_funcs.setdefault(None, []).append(f)541+ return f542+543+ @setupmethod544+ def context_processor(545+ self,546+ f: T_template_context_processor,547+ ) -> T_template_context_processor:548+ """Registers a template context processor function. These functions run before549+ rendering a template. The keys of the returned dict are added as variables550+ available in the template.551+552+ This is available on both app and blueprint objects. When used on an app, this553+ is called for every rendered template. When used on a blueprint, this is called554+ for templates rendered from the blueprint's views. To register with a blueprint555+ and affect every template, use :meth:`.Blueprint.app_context_processor`.556+ """557+ self.template_context_processors[None].append(f)558+ return f559+560+ @setupmethod561+ def url_value_preprocessor(562+ self,563+ f: T_url_value_preprocessor,564+ ) -> T_url_value_preprocessor:565+ """Register a URL value preprocessor function for all view566+ functions in the application. These functions will be called before the567+ :meth:`before_request` functions.568+569+ The function can modify the values captured from the matched url before570+ they are passed to the view. For example, this can be used to pop a571+ common language code value and place it in ``g`` rather than pass it to572+ every view.573+574+ The function is passed the endpoint name and values dict. The return575+ value is ignored.576+577+ This is available on both app and blueprint objects. When used on an app, this578+ is called for every request. When used on a blueprint, this is called for579+ requests that the blueprint handles. To register with a blueprint and affect580+ every request, use :meth:`.Blueprint.app_url_value_preprocessor`.581+ """582+ self.url_value_preprocessors[None].append(f)583+ return f584+585+ @setupmethod586+ def url_defaults(self, f: T_url_defaults) -> T_url_defaults:587+ """Callback function for URL defaults for all view functions of the588+ application. It's called with the endpoint and values and should589+ update the values passed in place.590+591+ This is available on both app and blueprint objects. When used on an app, this592+ is called for every request. When used on a blueprint, this is called for593+ requests that the blueprint handles. To register with a blueprint and affect594+ every request, use :meth:`.Blueprint.app_url_defaults`.595+ """596+ self.url_default_functions[None].append(f)597+ return f598+599+ @setupmethod600+ def errorhandler(601+ self, code_or_exception: type[Exception] | int602+ ) -> t.Callable[[T_error_handler], T_error_handler]:603+ """Register a function to handle errors by code or exception class.604+605+ A decorator that is used to register a function given an606+ error code. Example::607+608+ @app.errorhandler(404)609+ def page_not_found(error):610+ return 'This page does not exist', 404611+612+ You can also register handlers for arbitrary exceptions::613+614+ @app.errorhandler(DatabaseError)615+ def special_exception_handler(error):616+ return 'Database connection failed', 500617+618+ This is available on both app and blueprint objects. When used on an app, this619+ can handle errors from every request. When used on a blueprint, this can handle620+ errors from requests that the blueprint handles. To register with a blueprint621+ and affect every request, use :meth:`.Blueprint.app_errorhandler`.622+623+ .. versionadded:: 0.7624+ Use :meth:`register_error_handler` instead of modifying625+ :attr:`error_handler_spec` directly, for application wide error626+ handlers.627+628+ .. versionadded:: 0.7629+ One can now additionally also register custom exception types630+ that do not necessarily have to be a subclass of the631+ :class:`~werkzeug.exceptions.HTTPException` class.632+633+ :param code_or_exception: the code as integer for the handler, or634+ an arbitrary exception635+ """636+637+ def decorator(f: T_error_handler) -> T_error_handler:638+ self.register_error_handler(code_or_exception, f)639+ return f640+641+ return decorator642+643+ @setupmethod644+ def register_error_handler(645+ self,646+ code_or_exception: type[Exception] | int,647+ f: ft.ErrorHandlerCallable,648+ ) -> None:649+ """Alternative error attach function to the :meth:`errorhandler`650+ decorator that is more straightforward to use for non decorator651+ usage.652+653+ .. versionadded:: 0.7654+ """655+ exc_class, code = self._get_exc_class_and_code(code_or_exception)656+ self.error_handler_spec[None][code][exc_class] = f657+658+ @staticmethod659+ def _get_exc_class_and_code(660+ exc_class_or_code: type[Exception] | int,661+ ) -> tuple[type[Exception], int | None]:662+ """Get the exception class being handled. For HTTP status codes663+ or ``HTTPException`` subclasses, return both the exception and664+ status code.665+666+ :param exc_class_or_code: Any exception class, or an HTTP status667+ code as an integer.668+ """669+ exc_class: type[Exception]670+671+ if isinstance(exc_class_or_code, int):672+ try:673+ exc_class = default_exceptions[exc_class_or_code]674+ except KeyError:675+ raise ValueError(676+ f"'{exc_class_or_code}' is not a recognized HTTP"677+ " error code. Use a subclass of HTTPException with"678+ " that code instead."679+ ) from None680+ else:681+ exc_class = exc_class_or_code682+683+ if isinstance(exc_class, Exception):684+ raise TypeError(685+ f"{exc_class!r} is an instance, not a class. Handlers"686+ " can only be registered for Exception classes or HTTP"687+ " error codes."688+ )689+690+ if not issubclass(exc_class, Exception):691+ raise ValueError(692+ f"'{exc_class.__name__}' is not a subclass of Exception."693+ " Handlers can only be registered for Exception classes"694+ " or HTTP error codes."695+ )696+697+ if issubclass(exc_class, HTTPException):698+ return exc_class, exc_class.code699+ else:700+ return exc_class, None701+702+703+def _endpoint_from_view_func(view_func: t.Callable) -> str:704+ """Internal helper that returns the default endpoint for a given705+ function. This always is the function name.706+ """707+ assert view_func is not None, "expected view func if endpoint is not provided."708+ return view_func.__name__709+710+711+def _path_is_relative_to(path: pathlib.PurePath, base: str) -> bool:712+ # Path.is_relative_to doesn't exist until Python 3.9713+ try:714+ path.relative_to(base)715+ return True716+ except ValueError:717+ return False718+719+720+def _find_package_path(import_name):721+ """Find the path that contains the package or module."""722+ root_mod_name, _, _ = import_name.partition(".")723+724+ try:725+ root_spec = importlib.util.find_spec(root_mod_name)726+727+ if root_spec is None:728+ raise ValueError("not found")729+ except (ImportError, ValueError):730+ # ImportError: the machinery told us it does not exist731+ # ValueError:732+ # - the module name was invalid733+ # - the module name is __main__734+ # - we raised `ValueError` due to `root_spec` being `None`735+ return os.getcwd()736+737+ if root_spec.origin in {"namespace", None}:738+ # namespace package739+ package_spec = importlib.util.find_spec(import_name)740+741+ if package_spec is not None and package_spec.submodule_search_locations:742+ # Pick the path in the namespace that contains the submodule.743+ package_path = pathlib.Path(744+ os.path.commonpath(package_spec.submodule_search_locations)745+ )746+ search_location = next(747+ location748+ for location in root_spec.submodule_search_locations749+ if _path_is_relative_to(package_path, location)750+ )751+ else:752+ # Pick the first path.753+ search_location = root_spec.submodule_search_locations[0]754+755+ return os.path.dirname(search_location)756+ elif root_spec.submodule_search_locations:757+ # package with __init__.py758+ return os.path.dirname(os.path.dirname(root_spec.origin))759+ else:760+ # module761+ return os.path.dirname(root_spec.origin)762+763+764+def find_package(import_name: str):765+ """Find the prefix that a package is installed under, and the path766+ that it would be imported from.767+768+ The prefix is the directory containing the standard directory769+ hierarchy (lib, bin, etc.). If the package is not installed to the770+ system (:attr:`sys.prefix`) or a virtualenv (``site-packages``),771+ ``None`` is returned.772+773+ The path is the entry in :attr:`sys.path` that contains the package774+ for import. If the package is not installed, it's assumed that the775+ package was imported from the current working directory.776+ """777+ package_path = _find_package_path(import_name)778+ py_prefix = os.path.abspath(sys.prefix)779+780+ # installed to the system781+ if _path_is_relative_to(pathlib.PurePath(package_path), py_prefix):782+ return py_prefix, package_path783+784+ site_parent, site_folder = os.path.split(package_path)785+786+ # installed to a virtualenv787+ if site_folder.lower() == "site-packages":788+ parent, folder = os.path.split(site_parent)789+790+ # Windows (prefix/lib/site-packages)791+ if folder.lower() == "lib":792+ return parent, package_path793+794+ # Unix (prefix/lib/pythonX.Y/site-packages)795+ if os.path.basename(parent).lower() == "lib":796+ return os.path.dirname(parent), package_path797+798+ # something else (prefix/site-packages)799+ return site_parent, package_path800+801+ # not installed802+ return None, package_pathmodified:src/flask/__init__.py+2 added-2 removed
1 from . import json as json2 from .app import Flask as Flask3-from .app import Request as Request4-from .app import Response as Response3 from .blueprints import Blueprint as Blueprint4 from .config import Config as Config5 from .ctx import after_this_request as after_this_request6 from .ctx import copy_current_request_context as copy_current_request_context27 unmodified lines34 from .templating import render_template as render_template35 from .templating import render_template_string as render_template_string36 from .templating import stream_template as stream_template37 from .templating import stream_template_string as stream_template_string38+from .wrappers import Request as Request39+from .wrappers import Response as Response40 41 __version__ = "3.0.0.dev"modified:src/flask/app.py+137 added-853 removed
1 from __future__ import annotations2 3-import logging3 import os4 import sys5 import typing as t6 import weakref6 unmodified lines13 14 import click15 from werkzeug.datastructures import Headers16 from werkzeug.datastructures import ImmutableDict18-from werkzeug.exceptions import Aborter19-from werkzeug.exceptions import BadRequest17 from werkzeug.exceptions import BadRequestKeyError18 from werkzeug.exceptions import HTTPException19 from werkzeug.exceptions import InternalServerError20 from werkzeug.routing import BuildError24-from werkzeug.routing import Map21 from werkzeug.routing import MapAdapter22 from werkzeug.routing import RequestRedirect23 from werkzeug.routing import RoutingException24 from werkzeug.routing import Rule25 from werkzeug.serving import is_running_from_reloader30-from werkzeug.utils import cached_property31-from werkzeug.utils import redirect as _wz_redirect26 from werkzeug.wrappers import Response as BaseResponse27 28 from . import cli29 from . import typing as ft36-from .config import Config37-from .config import ConfigAttribute38-from .ctx import _AppCtxGlobals30 from .ctx import AppContext31 from .ctx import RequestContext32 from .globals import _cv_app33 from .globals import _cv_request34+from .globals import current_app35 from .globals import g36 from .globals import request37 from .globals import request_ctx38 from .globals import session47-from .helpers import _split_blueprint_path39 from .helpers import get_debug_flag40 from .helpers import get_flashed_messages41 from .helpers import get_load_dotenv51-from .json.provider import DefaultJSONProvider52-from .json.provider import JSONProvider53-from .logging import create_logger54-from .scaffold import _endpoint_from_view_func55-from .scaffold import _sentinel56-from .scaffold import find_package57-from .scaffold import Scaffold58-from .scaffold import setupmethod42+from .helpers import send_from_directory43+from .sansio.app import App44+from .sansio.scaffold import _sentinel45 from .sessions import SecureCookieSessionInterface46 from .sessions import SessionInterface47 from .signals import appcontext_tearing_down48 from .signals import got_request_exception49 from .signals import request_finished50 from .signals import request_started51 from .signals import request_tearing_down66-from .templating import DispatchingJinjaLoader52 from .templating import Environment53 from .wrappers import Request54 from .wrappers import Response55 56 if t.TYPE_CHECKING: # pragma: no cover72- from .blueprints import Blueprint57 from .testing import FlaskClient58 from .testing import FlaskCliRunner59 60 T_shell_context_processor = t.TypeVar(11 unmodified lines72 73 return timedelta(seconds=value)74 75 92-class Flask(Scaffold):76+class Flask(App):77 """The flask object implements a WSGI application and acts as the central78 object. It is passed the name of the module or package of the79 application. Once it is created it will act as a central registry for80 the view functions, the URL rules, template configuration and much more.88 unmodified lines169 This should only be set manually when it can't be detected170 automatically, such as for namespace packages.171 """172 189- #: The class that is used for request objects. See :class:`~flask.Request`190- #: for more information.191- request_class = Request192-193- #: The class that is used for response objects. See194- #: :class:`~flask.Response` for more information.195- response_class = Response196-197- #: The class of the object assigned to :attr:`aborter`, created by198- #: :meth:`create_aborter`. That object is called by199- #: :func:`flask.abort` to raise HTTP errors, and can be200- #: called directly as well.201- #:202- #: Defaults to :class:`werkzeug.exceptions.Aborter`.203- #:204- #: .. versionadded:: 2.2205- aborter_class = Aborter206-207- #: The class that is used for the Jinja environment.208- #:209- #: .. versionadded:: 0.11210- jinja_environment = Environment211-212- #: The class that is used for the :data:`~flask.g` instance.213- #:214- #: Example use cases for a custom class:215- #:216- #: 1. Store arbitrary attributes on flask.g.217- #: 2. Add a property for lazy per-request database connectors.218- #: 3. Return None instead of AttributeError on unexpected attributes.219- #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g.220- #:221- #: In Flask 0.9 this property was called `request_globals_class` but it222- #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the223- #: flask.g object is now application context scoped.224- #:225- #: .. versionadded:: 0.10226- app_ctx_globals_class = _AppCtxGlobals227-228- #: The class that is used for the ``config`` attribute of this app.229- #: Defaults to :class:`~flask.Config`.230- #:231- #: Example use cases for a custom class:232- #:233- #: 1. Default values for certain config options.234- #: 2. Access to config values through attributes in addition to keys.235- #:236- #: .. versionadded:: 0.11237- config_class = Config238-239- #: The testing flag. Set this to ``True`` to enable the test mode of240- #: Flask extensions (and in the future probably also Flask itself).241- #: For example this might activate test helpers that have an242- #: additional runtime cost which should not be enabled by default.243- #:244- #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the245- #: default it's implicitly enabled.246- #:247- #: This attribute can also be configured from the config with the248- #: ``TESTING`` configuration key. Defaults to ``False``.249- testing = ConfigAttribute("TESTING")250-251- #: If a secret key is set, cryptographic components can use this to252- #: sign cookies and other things. Set this to a complex random value253- #: when you want to use the secure cookie for instance.254- #:255- #: This attribute can also be configured from the config with the256- #: :data:`SECRET_KEY` configuration key. Defaults to ``None``.257- secret_key = ConfigAttribute("SECRET_KEY")258-259- #: A :class:`~datetime.timedelta` which is used to set the expiration260- #: date of a permanent session. The default is 31 days which makes a261- #: permanent session survive for roughly one month.262- #:263- #: This attribute can also be configured from the config with the264- #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to265- #: ``timedelta(days=31)``266- permanent_session_lifetime = ConfigAttribute(267- "PERMANENT_SESSION_LIFETIME", get_converter=_make_timedelta268- )269-270- json_provider_class: type[JSONProvider] = DefaultJSONProvider271- """A subclass of :class:`~flask.json.provider.JSONProvider`. An272- instance is created and assigned to :attr:`app.json` when creating273- the app.274-275- The default, :class:`~flask.json.provider.DefaultJSONProvider`, uses276- Python's built-in :mod:`json` library. A different provider can use277- a different JSON library.278-279- .. versionadded:: 2.2280- """281-282- #: Options that are passed to the Jinja environment in283- #: :meth:`create_jinja_environment`. Changing these options after284- #: the environment is created (accessing :attr:`jinja_env`) will285- #: have no effect.286- #:287- #: .. versionchanged:: 1.1.0288- #: This is a ``dict`` instead of an ``ImmutableDict`` to allow289- #: easier configuration.290- #:291- jinja_options: dict = {}292-293- #: Default configuration parameters.173 default_config = ImmutableDict(174 {175 "DEBUG": None,176 "TESTING": False,20 unmodified lines197 "MAX_COOKIE_SIZE": 4093,198 }199 )200 322- #: The rule object to use for URL rules created. This is used by323- #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.324- #:325- #: .. versionadded:: 0.7326- url_rule_class = Rule201+ #: The class that is used for request objects. See :class:`~flask.Request`202+ #: for more information.203+ request_class = Request204 328- #: The map object to use for storing the URL rules and routing329- #: configuration parameters. Defaults to :class:`werkzeug.routing.Map`.330- #:331- #: .. versionadded:: 1.1.0332- url_map_class = Map205+ #: The class that is used for response objects. See206+ #: :class:`~flask.Response` for more information.207+ response_class = Response208 334- #: The :meth:`test_client` method creates an instance of this test335- #: client class. Defaults to :class:`~flask.testing.FlaskClient`.336- #:337- #: .. versionadded:: 0.7338- test_client_class: type[FlaskClient] | None = None339-340- #: The :class:`~click.testing.CliRunner` subclass, by default341- #: :class:`~flask.testing.FlaskCliRunner` that is used by342- #: :meth:`test_cli_runner`. Its ``__init__`` method should take a343- #: Flask app object as the first argument.344- #:345- #: .. versionadded:: 1.0346- test_cli_runner_class: type[FlaskCliRunner] | None = None347-209 #: the session interface to use. By default an instance of210 #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.211 #:212 #: .. versionadded:: 0.813 unmodified lines226 root_path: str | None = None,227 ):228 super().__init__(229 import_name=import_name,369- static_folder=static_folder,230 static_url_path=static_url_path,231+ static_folder=static_folder,232+ static_host=static_host,233+ host_matching=host_matching,234+ subdomain_matching=subdomain_matching,235 template_folder=template_folder,236+ instance_path=instance_path,237+ instance_relative_config=instance_relative_config,238 root_path=root_path,239 )240 375- if instance_path is None:376- instance_path = self.auto_find_instance_path()377- elif not os.path.isabs(instance_path):378- raise ValueError(379- "If an instance path is provided it must be absolute."380- " A relative path was given instead."381- )382-383- #: Holds the path to the instance folder.384- #:385- #: .. versionadded:: 0.8386- self.instance_path = instance_path387-388- #: The configuration dictionary as :class:`Config`. This behaves389- #: exactly like a regular dictionary but supports additional methods390- #: to load a config from files.391- self.config = self.make_config(instance_relative_config)392-393- #: An instance of :attr:`aborter_class` created by394- #: :meth:`make_aborter`. This is called by :func:`flask.abort`395- #: to raise HTTP errors, and can be called directly as well.396- #:397- #: .. versionadded:: 2.2398- #: Moved from ``flask.abort``, which calls this object.399- self.aborter = self.make_aborter()400-401- self.json: JSONProvider = self.json_provider_class(self)402- """Provides access to JSON methods. Functions in ``flask.json``403- will call methods on this provider when the application context404- is active. Used for handling JSON requests and responses.405-406- An instance of :attr:`json_provider_class`. Can be customized by407- changing that attribute on a subclass, or by assigning to this408- attribute afterwards.409-410- The default, :class:`~flask.json.provider.DefaultJSONProvider`,411- uses Python's built-in :mod:`json` library. A different provider412- can use a different JSON library.413-414- .. versionadded:: 2.2415- """416-417- #: A list of functions that are called by418- #: :meth:`handle_url_build_error` when :meth:`.url_for` raises a419- #: :exc:`~werkzeug.routing.BuildError`. Each function is called420- #: with ``error``, ``endpoint`` and ``values``. If a function421- #: returns ``None`` or raises a ``BuildError``, it is skipped.422- #: Otherwise, its return value is returned by ``url_for``.423- #:424- #: .. versionadded:: 0.9425- self.url_build_error_handlers: list[426- t.Callable[[Exception, str, dict[str, t.Any]], str]427- ] = []428-429- #: A list of functions that are called when the application context430- #: is destroyed. Since the application context is also torn down431- #: if the request ends this is the place to store code that disconnects432- #: from databases.433- #:434- #: .. versionadded:: 0.9435- self.teardown_appcontext_funcs: list[ft.TeardownCallable] = []436-437- #: A list of shell context processor functions that should be run438- #: when a shell context is created.439- #:440- #: .. versionadded:: 0.11441- self.shell_context_processors: list[ft.ShellContextProcessorCallable] = []442-443- #: Maps registered blueprint names to blueprint objects. The444- #: dict retains the order the blueprints were registered in.445- #: Blueprints can be registered multiple times, this dict does446- #: not track how often they were attached.447- #:448- #: .. versionadded:: 0.7449- self.blueprints: dict[str, Blueprint] = {}450-451- #: a place where extensions can store application specific state. For452- #: example this is where an extension could store database engines and453- #: similar things.454- #:455- #: The key must match the name of the extension module. For example in456- #: case of a "Flask-Foo" extension in `flask_foo`, the key would be457- #: ``'foo'``.458- #:459- #: .. versionadded:: 0.7460- self.extensions: dict = {}461-462- #: The :class:`~werkzeug.routing.Map` for this instance. You can use463- #: this to change the routing converters after the class was created464- #: but before any routes are connected. Example::465- #:466- #: from werkzeug.routing import BaseConverter467- #:468- #: class ListConverter(BaseConverter):469- #: def to_python(self, value):470- #: return value.split(',')471- #: def to_url(self, values):472- #: return ','.join(super(ListConverter, self).to_url(value)473- #: for value in values)474- #:475- #: app = Flask(__name__)476- #: app.url_map.converters['list'] = ListConverter477- self.url_map = self.url_map_class()478-479- self.url_map.host_matching = host_matching480- self.subdomain_matching = subdomain_matching481-482- # tracks internally if the application already handled at least one483- # request.484- self._got_first_request = False485-241 # Add a static route using the provided static_url_path, static_host,242 # and static_folder if there is a configured static_folder.243 # Note we do this without checking if static_folder exists.244 # For one, it might be created while the server is running (e.g. during11 unmodified lines256 host=static_host,257 view_func=lambda **kw: self_ref().send_static_file(**kw), # type: ignore # noqa: B950258 )259 505- # Set the name of the Click group in case someone wants to add506- # the app's commands to another CLI tool.507- self.cli.name = self.name260+ def get_send_file_max_age(self, filename: str | None) -> int | None:261+ """Used by :func:`send_file` to determine the ``max_age`` cache262+ value for a given file path if it wasn't passed.263 509- def _check_setup_finished(self, f_name: str) -> None:510- if self._got_first_request:511- raise AssertionError(512- f"The setup method '{f_name}' can no longer be called"513- " on the application. It has already handled its first"514- " request, any changes will not be applied"515- " consistently.\n"516- "Make sure all imports, decorators, functions, etc."517- " needed to set up the application are done before"518- " running it."519- )264+ By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from265+ the configuration of :data:`~flask.current_app`. This defaults266+ to ``None``, which tells the browser to use conditional requests267+ instead of a timed cache, which is usually preferable.268 521- @cached_property522- def name(self) -> str: # type: ignore523- """The name of the application. This is usually the import name524- with the difference that it's guessed from the run file if the525- import name is main. This name is used as a display name when526- Flask needs the name of the application. It can be set and overridden527- to change the value.269+ Note this is a duplicate of the same method in the Flask270+ class.271 272+ .. versionchanged:: 2.0273+ The default configuration is ``None`` instead of 12 hours.274+529- .. versionadded:: 0.8275+ .. versionadded:: 0.9276 """531- if self.import_name == "__main__":532- fn = getattr(sys.modules["__main__"], "__file__", None)533- if fn is None:534- return "__main__"535- return os.path.splitext(os.path.basename(fn))[0]536- return self.import_name277+ value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]278 538- @cached_property539- def logger(self) -> logging.Logger:540- """A standard Python :class:`~logging.Logger` for the app, with541- the same name as :attr:`name`.279+ if value is None:280+ return None281 543- In debug mode, the logger's :attr:`~logging.Logger.level` will544- be set to :data:`~logging.DEBUG`.282+ if isinstance(value, timedelta):283+ return int(value.total_seconds())284 546- If there are no handlers configured, a default handler will be547- added. See :doc:`/logging` for more information.285+ return value286 549- .. versionchanged:: 1.1.0550- The logger takes the same name as :attr:`name` rather than551- hard-coding ``"flask.app"``.287+ def send_static_file(self, filename: str) -> Response:288+ """The view function used to serve files from289+ :attr:`static_folder`. A route is automatically registered for290+ this view at :attr:`static_url_path` if :attr:`static_folder` is291+ set.292 553- .. versionchanged:: 1.0.0554- Behavior was simplified. The logger is always named555- ``"flask.app"``. The level is only set during configuration,556- it doesn't check ``app.debug`` each time. Only one format is557- used, not different ones depending on ``app.debug``. No558- handlers are removed, and a handler is only added if no559- handlers are already configured.293+ Note this is a duplicate of the same method in the Flask294+ class.295 561- .. versionadded:: 0.3562- """563- return create_logger(self)296+ .. versionadded:: 0.5297 565- @cached_property566- def jinja_env(self) -> Environment:567- """The Jinja environment used to load templates.568-569- The environment is created the first time this property is570- accessed. Changing :attr:`jinja_options` after that will have no571- effect.298 """573- return self.create_jinja_environment()299+ if not self.has_static_folder:300+ raise RuntimeError("'static_folder' must be set to serve static_files.")301 575- def make_config(self, instance_relative: bool = False) -> Config:576- """Used to create the config attribute by the Flask constructor.577- The `instance_relative` parameter is passed in from the constructor578- of Flask (there named `instance_relative_config`) and indicates if579- the config should be relative to the instance path or the root path580- of the application.302+ # send_file only knows to call get_send_file_max_age on the app,303+ # call it here so it works for blueprints too.304+ max_age = self.get_send_file_max_age(filename)305+ return send_from_directory(306+ t.cast(str, self.static_folder), filename, max_age=max_age307+ )308 582- .. versionadded:: 0.8583- """584- root_path = self.root_path585- if instance_relative:586- root_path = self.instance_path587- defaults = dict(self.default_config)588- defaults["DEBUG"] = get_debug_flag()589- return self.config_class(root_path, defaults)309+ def open_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:310+ """Open a resource file relative to :attr:`root_path` for311+ reading.312 591- def make_aborter(self) -> Aborter:592- """Create the object to assign to :attr:`aborter`. That object593- is called by :func:`flask.abort` to raise HTTP errors, and can594- be called directly as well.313+ For example, if the file ``schema.sql`` is next to the file314+ ``app.py`` where the ``Flask`` app is defined, it can be opened315+ with:316 596- By default, this creates an instance of :attr:`aborter_class`,597- which defaults to :class:`werkzeug.exceptions.Aborter`.317+ .. code-block:: python318 599- .. versionadded:: 2.2600- """601- return self.aborter_class()319+ with app.open_resource("schema.sql") as f:320+ conn.executescript(f.read())321 603- def auto_find_instance_path(self) -> str:604- """Tries to locate the instance path if it was not provided to the605- constructor of the application class. It will basically calculate606- the path to a folder named ``instance`` next to your main file or607- the package.322+ :param resource: Path to the resource relative to323+ :attr:`root_path`.324+ :param mode: Open the file in this mode. Only reading is325+ supported, valid values are "r" (or "rt") and "rb".326 609- .. versionadded:: 0.8327+ Note this is a duplicate of the same method in the Flask328+ class.329+330 """611- prefix, package_path = find_package(self.import_name)612- if prefix is None:613- return os.path.join(package_path, "instance")614- return os.path.join(prefix, "var", f"{self.name}-instance")331+ if mode not in {"r", "rt", "rb"}:332+ raise ValueError("Resources can only be opened for reading.")333 334+ return open(os.path.join(self.root_path, resource), mode)335+336 def open_instance_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:337 """Opens a resource from the application's instance folder338 (:attr:`instance_path`). Otherwise works like339 :meth:`open_resource`. Instance resources can also be opened for44 unmodified lines384 )385 rv.policies["json.dumps_function"] = self.json.dumps386 return rv387 668- def create_global_jinja_loader(self) -> DispatchingJinjaLoader:669- """Creates the loader for the Jinja2 environment. Can be used to670- override just the loader and keeping the rest unchanged. It's671- discouraged to override this function. Instead one should override672- the :meth:`jinja_loader` function instead.388+ def create_url_adapter(self, request: Request | None) -> MapAdapter | None:389+ """Creates a URL adapter for the given request. The URL adapter390+ is created at a point where the request context is not yet set391+ up so the request is passed explicitly.392 674- The global loader dispatches between the loaders of the application675- and the individual blueprints.393+ .. versionadded:: 0.6394 677- .. versionadded:: 0.7395+ .. versionchanged:: 0.9396+ This can now also be called without a request object when the397+ URL adapter is created for the application context.398+399+ .. versionchanged:: 1.0400+ :data:`SERVER_NAME` no longer implicitly enables subdomain401+ matching. Use :attr:`subdomain_matching` instead.402 """679- return DispatchingJinjaLoader(self)403+ if request is not None:404+ # If subdomain matching is disabled (the default), use the405+ # default subdomain in all cases. This should be the default406+ # in Werkzeug but it currently does not have that feature.407+ if not self.subdomain_matching:408+ subdomain = self.url_map.default_subdomain or None409+ else:410+ subdomain = None411 681- def select_jinja_autoescape(self, filename: str) -> bool:682- """Returns ``True`` if autoescaping should be active for the given683- template name. If no template name is given, returns `True`.412+ print(self.config["SERVER_NAME"], subdomain)413+ return self.url_map.bind_to_environ(414+ request.environ,415+ server_name=self.config["SERVER_NAME"],416+ subdomain=subdomain,417+ )418+ # We need at the very least the server name to be set for this419+ # to work.420+ if self.config["SERVER_NAME"] is not None:421+ return self.url_map.bind(422+ self.config["SERVER_NAME"],423+ script_name=self.config["APPLICATION_ROOT"],424+ url_scheme=self.config["PREFERRED_URL_SCHEME"],425+ )426 685- .. versionchanged:: 2.2686- Autoescaping is now enabled by default for ``.svg`` files.427+ return None428 688- .. versionadded:: 0.5429+ def raise_routing_exception(self, request: Request) -> t.NoReturn:430+ """Intercept routing exceptions and possibly do something else.431+432+ In debug mode, intercept a routing redirect and replace it with433+ an error if the body will be discarded.434+435+ With modern Werkzeug this shouldn't occur, since it now uses a436+ 308 status which tells the browser to resend the method and437+ body.438+439+ .. versionchanged:: 2.1440+ Don't intercept 307 and 308 redirects.441+442+ :meta private:443+ :internal:444 """690- if filename is None:691- return True692- return filename.endswith((".html", ".htm", ".xml", ".xhtml", ".svg"))445+ if (446+ not self.debug447+ or not isinstance(request.routing_exception, RequestRedirect)448+ or request.routing_exception.code in {307, 308}449+ or request.method in {"GET", "HEAD", "OPTIONS"}450+ ):451+ raise request.routing_exception # type: ignore452 453+ from .debughelpers import FormDataRoutingRedirect454+455+ raise FormDataRoutingRedirect(request)456+457 def update_template_context(self, context: dict) -> None:458 """Update the template context with some commonly used variables.459 This injects request, session, config and g into the template460 context as well as everything template context processors want16 unmodified lines477 478 for name in names:479 if name in self.template_context_processors:480 for func in self.template_context_processors[name]:718- context.update(func())481+ context.update(self.ensure_sync(func)())482 483 context.update(orig_ctx)484 485 def make_shell_context(self) -> dict:7 unmodified lines493 for processor in self.shell_context_processors:494 rv.update(processor())495 return rv496 734- @property735- def debug(self) -> bool:736- """Whether debug mode is enabled. When using ``flask run`` to start the737- development server, an interactive debugger will be shown for unhandled738- exceptions, and the server will be reloaded when code changes. This maps to the739- :data:`DEBUG` config key. It may not behave as expected if set late.740-741- **Do not enable debug mode when deploying in production.**742-743- Default: ``False``744- """745- return self.config["DEBUG"]746-747- @debug.setter748- def debug(self, value: bool) -> None:749- self.config["DEBUG"] = value750-751- if self.config["TEMPLATES_AUTO_RELOAD"] is None:752- self.jinja_env.auto_reload = value753-497 def run(498 self,499 host: str | None = None,500 port: int | None = None,190 unmodified lines691 from .testing import FlaskCliRunner as cls692 693 return cls(self, **kwargs) # type: ignore694 952- @setupmethod953- def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:954- """Register a :class:`~flask.Blueprint` on the application. Keyword955- arguments passed to this method will override the defaults set on the956- blueprint.957-958- Calls the blueprint's :meth:`~flask.Blueprint.register` method after959- recording the blueprint in the application's :attr:`blueprints`.960-961- :param blueprint: The blueprint to register.962- :param url_prefix: Blueprint routes will be prefixed with this.963- :param subdomain: Blueprint routes will match on this subdomain.964- :param url_defaults: Blueprint routes will use these default values for965- view arguments.966- :param options: Additional keyword arguments are passed to967- :class:`~flask.blueprints.BlueprintSetupState`. They can be968- accessed in :meth:`~flask.Blueprint.record` callbacks.969-970- .. versionchanged:: 2.0.1971- The ``name`` option can be used to change the (pre-dotted)972- name the blueprint is registered with. This allows the same973- blueprint to be registered multiple times with unique names974- for ``url_for``.975-976- .. versionadded:: 0.7977- """978- blueprint.register(self, options)979-980- def iter_blueprints(self) -> t.ValuesView[Blueprint]:981- """Iterates over all blueprints by the order they were registered.982-983- .. versionadded:: 0.11984- """985- return self.blueprints.values()986-987- @setupmethod988- def add_url_rule(989- self,990- rule: str,991- endpoint: str | None = None,992- view_func: ft.RouteCallable | None = None,993- provide_automatic_options: bool | None = None,994- **options: t.Any,995- ) -> None:996- if endpoint is None:997- endpoint = _endpoint_from_view_func(view_func) # type: ignore998- options["endpoint"] = endpoint999- methods = options.pop("methods", None)1000-1001- # if the methods are not given and the view_func object knows its1002- # methods we can use that instead. If neither exists, we go with1003- # a tuple of only ``GET`` as default.1004- if methods is None:1005- methods = getattr(view_func, "methods", None) or ("GET",)1006- if isinstance(methods, str):1007- raise TypeError(1008- "Allowed methods must be a list of strings, for"1009- ' example: @app.route(..., methods=["POST"])'1010- )1011- methods = {item.upper() for item in methods}1012-1013- # Methods that should always be added1014- required_methods = set(getattr(view_func, "required_methods", ()))1015-1016- # starting with Flask 0.8 the view_func object can disable and1017- # force-enable the automatic options handling.1018- if provide_automatic_options is None:1019- provide_automatic_options = getattr(1020- view_func, "provide_automatic_options", None1021- )1022-1023- if provide_automatic_options is None:1024- if "OPTIONS" not in methods:1025- provide_automatic_options = True1026- required_methods.add("OPTIONS")1027- else:1028- provide_automatic_options = False1029-1030- # Add the required methods now.1031- methods |= required_methods1032-1033- rule = self.url_rule_class(rule, methods=methods, **options)1034- rule.provide_automatic_options = provide_automatic_options # type: ignore1035-1036- self.url_map.add(rule)1037- if view_func is not None:1038- old_func = self.view_functions.get(endpoint)1039- if old_func is not None and old_func != view_func:1040- raise AssertionError(1041- "View function mapping is overwriting an existing"1042- f" endpoint function: {endpoint}"1043- )1044- self.view_functions[endpoint] = view_func1045-1046- @setupmethod1047- def template_filter(1048- self, name: str | None = None1049- ) -> t.Callable[[T_template_filter], T_template_filter]:1050- """A decorator that is used to register custom template filter.1051- You can specify a name for the filter, otherwise the function1052- name will be used. Example::1053-1054- @app.template_filter()1055- def reverse(s):1056- return s[::-1]1057-1058- :param name: the optional name of the filter, otherwise the1059- function name will be used.1060- """1061-1062- def decorator(f: T_template_filter) -> T_template_filter:1063- self.add_template_filter(f, name=name)1064- return f1065-1066- return decorator1067-1068- @setupmethod1069- def add_template_filter(1070- self, f: ft.TemplateFilterCallable, name: str | None = None1071- ) -> None:1072- """Register a custom template filter. Works exactly like the1073- :meth:`template_filter` decorator.1074-1075- :param name: the optional name of the filter, otherwise the1076- function name will be used.1077- """1078- self.jinja_env.filters[name or f.__name__] = f1079-1080- @setupmethod1081- def template_test(1082- self, name: str | None = None1083- ) -> t.Callable[[T_template_test], T_template_test]:1084- """A decorator that is used to register custom template test.1085- You can specify a name for the test, otherwise the function1086- name will be used. Example::1087-1088- @app.template_test()1089- def is_prime(n):1090- if n == 2:1091- return True1092- for i in range(2, int(math.ceil(math.sqrt(n))) + 1):1093- if n % i == 0:1094- return False1095- return True1096-1097- .. versionadded:: 0.101098-1099- :param name: the optional name of the test, otherwise the1100- function name will be used.1101- """1102-1103- def decorator(f: T_template_test) -> T_template_test:1104- self.add_template_test(f, name=name)1105- return f1106-1107- return decorator1108-1109- @setupmethod1110- def add_template_test(1111- self, f: ft.TemplateTestCallable, name: str | None = None1112- ) -> None:1113- """Register a custom template test. Works exactly like the1114- :meth:`template_test` decorator.1115-1116- .. versionadded:: 0.101117-1118- :param name: the optional name of the test, otherwise the1119- function name will be used.1120- """1121- self.jinja_env.tests[name or f.__name__] = f1122-1123- @setupmethod1124- def template_global(1125- self, name: str | None = None1126- ) -> t.Callable[[T_template_global], T_template_global]:1127- """A decorator that is used to register a custom template global function.1128- You can specify a name for the global function, otherwise the function1129- name will be used. Example::1130-1131- @app.template_global()1132- def double(n):1133- return 2 * n1134-1135- .. versionadded:: 0.101136-1137- :param name: the optional name of the global function, otherwise the1138- function name will be used.1139- """1140-1141- def decorator(f: T_template_global) -> T_template_global:1142- self.add_template_global(f, name=name)1143- return f1144-1145- return decorator1146-1147- @setupmethod1148- def add_template_global(1149- self, f: ft.TemplateGlobalCallable, name: str | None = None1150- ) -> None:1151- """Register a custom template global function. Works exactly like the1152- :meth:`template_global` decorator.1153-1154- .. versionadded:: 0.101155-1156- :param name: the optional name of the global function, otherwise the1157- function name will be used.1158- """1159- self.jinja_env.globals[name or f.__name__] = f1160-1161- @setupmethod1162- def teardown_appcontext(self, f: T_teardown) -> T_teardown:1163- """Registers a function to be called when the application1164- context is popped. The application context is typically popped1165- after the request context for each request, at the end of CLI1166- commands, or after a manually pushed context ends.1167-1168- .. code-block:: python1169-1170- with app.app_context():1171- ...1172-1173- When the ``with`` block exits (or ``ctx.pop()`` is called), the1174- teardown functions are called just before the app context is1175- made inactive. Since a request context typically also manages an1176- application context it would also be called when you pop a1177- request context.1178-1179- When a teardown function was called because of an unhandled1180- exception it will be passed an error object. If an1181- :meth:`errorhandler` is registered, it will handle the exception1182- and the teardown will not receive it.1183-1184- Teardown functions must avoid raising exceptions. If they1185- execute code that might fail they must surround that code with a1186- ``try``/``except`` block and log any errors.1187-1188- The return values of teardown functions are ignored.1189-1190- .. versionadded:: 0.91191- """1192- self.teardown_appcontext_funcs.append(f)1193- return f1194-1195- @setupmethod1196- def shell_context_processor(1197- self, f: T_shell_context_processor1198- ) -> T_shell_context_processor:1199- """Registers a shell context processor function.1200-1201- .. versionadded:: 0.111202- """1203- self.shell_context_processors.append(f)1204- return f1205-1206- def _find_error_handler(self, e: Exception) -> ft.ErrorHandlerCallable | None:1207- """Return a registered error handler for an exception in this order:1208- blueprint handler for a specific code, app handler for a specific code,1209- blueprint handler for an exception class, app handler for an exception1210- class, or ``None`` if a suitable handler is not found.1211- """1212- exc_class, code = self._get_exc_class_and_code(type(e))1213- names = (*request.blueprints, None)1214-1215- for c in (code, None) if code is not None else (None,):1216- for name in names:1217- handler_map = self.error_handler_spec[name][c]1218-1219- if not handler_map:1220- continue1221-1222- for cls in exc_class.__mro__:1223- handler = handler_map.get(cls)1224-1225- if handler is not None:1226- return handler1227- return None1228-695 def handle_http_exception(696 self, e: HTTPException697 ) -> HTTPException | ft.ResponseReturnValue:698 """Handles an HTTP exception. By default this will invoke the22 unmodified lines721 # are not raised or handled in user code.722 if isinstance(e, RoutingException):723 return e724 1259- handler = self._find_error_handler(e)725+ handler = self._find_error_handler(e, request.blueprints)726 if handler is None:727 return e728 return self.ensure_sync(handler)(e)729 1264- def trap_http_exception(self, e: Exception) -> bool:1265- """Checks if an HTTP exception should be trapped or not. By default1266- this will return ``False`` for all exceptions except for a bad request1267- key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It1268- also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.1269-1270- This is called for all HTTP exceptions raised by a view function.1271- If it returns ``True`` for any exception the error handler for this1272- exception is not called and it shows up as regular exception in the1273- traceback. This is helpful for debugging implicitly raised HTTP1274- exceptions.1275-1276- .. versionchanged:: 1.01277- Bad request errors are not trapped by default in debug mode.1278-1279- .. versionadded:: 0.81280- """1281- if self.config["TRAP_HTTP_EXCEPTIONS"]:1282- return True1283-1284- trap_bad_request = self.config["TRAP_BAD_REQUEST_ERRORS"]1285-1286- # if unset, trap key errors in debug mode1287- if (1288- trap_bad_request is None1289- and self.debug1290- and isinstance(e, BadRequestKeyError)1291- ):1292- return True1293-1294- if trap_bad_request:1295- return isinstance(e, BadRequest)1296-1297- return False1298-730 def handle_user_exception(731 self, e: Exception732 ) -> HTTPException | ft.ResponseReturnValue:733 """This method is called whenever an exception occurs that17 unmodified lines751 752 if isinstance(e, HTTPException) and not self.trap_http_exception(e):753 return self.handle_http_exception(e)754 1324- handler = self._find_error_handler(e)755+ handler = self._find_error_handler(e, request.blueprints)756 757 if handler is None:758 raise759 44 unmodified lines804 805 self.log_exception(exc_info)806 server_error: InternalServerError | ft.ResponseReturnValue807 server_error = InternalServerError(original_exception=e)1377- handler = self._find_error_handler(server_error)808+ handler = self._find_error_handler(server_error, request.blueprints)809 810 if handler is not None:811 server_error = self.ensure_sync(handler)(server_error)812 13 unmodified lines826 self.logger.error(827 f"Exception on {request.path} [{request.method}]", exc_info=exc_info828 )829 1399- def raise_routing_exception(self, request: Request) -> t.NoReturn:1400- """Intercept routing exceptions and possibly do something else.1401-1402- In debug mode, intercept a routing redirect and replace it with1403- an error if the body will be discarded.1404-1405- With modern Werkzeug this shouldn't occur, since it now uses a1406- 308 status which tells the browser to resend the method and1407- body.1408-1409- .. versionchanged:: 2.11410- Don't intercept 307 and 308 redirects.1411-1412- :meta private:1413- :internal:1414- """1415- if (1416- not self.debug1417- or not isinstance(request.routing_exception, RequestRedirect)1418- or request.routing_exception.code in {307, 308}1419- or request.method in {"GET", "HEAD", "OPTIONS"}1420- ):1421- raise request.routing_exception # type: ignore1422-1423- from .debughelpers import FormDataRoutingRedirect1424-1425- raise FormDataRoutingRedirect(request)1426-830 def dispatch_request(self) -> ft.ResponseReturnValue:831 """Does the request dispatching. Matches the URL and returns the832 return value of the view or error handler. This does not have to833 be a response object. In order to convert the return value to a79 unmodified lines913 rv = self.response_class()914 rv.allow.update(methods)915 return rv916 1514- def should_ignore_error(self, error: BaseException | None) -> bool:1515- """This is called to figure out if an error should be ignored1516- or not as far as the teardown system is concerned. If this1517- function returns ``True`` then the teardown handlers will not be1518- passed the error.1519-1520- .. versionadded:: 0.101521- """1522- return False1523-917 def ensure_sync(self, func: t.Callable) -> t.Callable:918 """Ensure that the function is synchronous for WSGI workers.919 Plain ``def`` functions are returned as-is. ``async def``920 functions are wrapped to run and wait for the response.154 unmodified lines1075 rv = f"{rv}#{_anchor}"1076 1077 return rv1078 1686- def redirect(self, location: str, code: int = 302) -> BaseResponse:1687- """Create a redirect response object.1688-1689- This is called by :func:`flask.redirect`, and can be called1690- directly as well.1691-1692- :param location: The URL to redirect to.1693- :param code: The status code for the redirect.1694-1695- .. versionadded:: 2.21696- Moved from ``flask.redirect``, which calls this method.1697- """1698- return _wz_redirect(location, code=code, Response=self.response_class)1699-1079 def make_response(self, rv: ft.ResponseReturnValue) -> Response:1080 """Convert the return value from a view function to an instance of1081 :attr:`response_class`.1082 132 unmodified lines1215 rv.headers.update(headers) # type: ignore[arg-type]1216 1217 return rv1218 1840- def create_url_adapter(self, request: Request | None) -> MapAdapter | None:1841- """Creates a URL adapter for the given request. The URL adapter1842- is created at a point where the request context is not yet set1843- up so the request is passed explicitly.1844-1845- .. versionadded:: 0.61846-1847- .. versionchanged:: 0.91848- This can now also be called without a request object when the1849- URL adapter is created for the application context.1850-1851- .. versionchanged:: 1.01852- :data:`SERVER_NAME` no longer implicitly enables subdomain1853- matching. Use :attr:`subdomain_matching` instead.1854- """1855- if request is not None:1856- # If subdomain matching is disabled (the default), use the1857- # default subdomain in all cases. This should be the default1858- # in Werkzeug but it currently does not have that feature.1859- if not self.subdomain_matching:1860- subdomain = self.url_map.default_subdomain or None1861- else:1862- subdomain = None1863-1864- return self.url_map.bind_to_environ(1865- request.environ,1866- server_name=self.config["SERVER_NAME"],1867- subdomain=subdomain,1868- )1869- # We need at the very least the server name to be set for this1870- # to work.1871- if self.config["SERVER_NAME"] is not None:1872- return self.url_map.bind(1873- self.config["SERVER_NAME"],1874- script_name=self.config["APPLICATION_ROOT"],1875- url_scheme=self.config["PREFERRED_URL_SCHEME"],1876- )1877-1878- return None1879-1880- def inject_url_defaults(self, endpoint: str, values: dict) -> None:1881- """Injects the URL defaults for the given endpoint directly into1882- the values dictionary passed. This is used internally and1883- automatically called on URL building.1884-1885- .. versionadded:: 0.71886- """1887- names: t.Iterable[str | None] = (None,)1888-1889- # url_for may be called outside a request context, parse the1890- # passed endpoint instead of using request.blueprints.1891- if "." in endpoint:1892- names = chain(1893- names, reversed(_split_blueprint_path(endpoint.rpartition(".")[0]))1894- )1895-1896- for name in names:1897- if name in self.url_default_functions:1898- for func in self.url_default_functions[name]:1899- func(endpoint, values)1900-1901- def handle_url_build_error(1902- self, error: BuildError, endpoint: str, values: dict[str, t.Any]1903- ) -> str:1904- """Called by :meth:`.url_for` if a1905- :exc:`~werkzeug.routing.BuildError` was raised. If this returns1906- a value, it will be returned by ``url_for``, otherwise the error1907- will be re-raised.1908-1909- Each function in :attr:`url_build_error_handlers` is called with1910- ``error``, ``endpoint`` and ``values``. If a function returns1911- ``None`` or raises a ``BuildError``, it is skipped. Otherwise,1912- its return value is returned by ``url_for``.1913-1914- :param error: The active ``BuildError`` being handled.1915- :param endpoint: The endpoint being built.1916- :param values: The keyword arguments passed to ``url_for``.1917- """1918- for handler in self.url_build_error_handlers:1919- try:1920- rv = handler(error, endpoint, values)1921- except BuildError as e:1922- # make error available outside except block1923- error = e1924- else:1925- if rv is not None:1926- return rv1927-1928- # Re-raise if called with an active exception, otherwise raise1929- # the passed in exception.1930- if error is sys.exc_info()[1]:1931- raise1932-1933- raise error1934-1219 def preprocess_request(self) -> ft.ResponseReturnValue | None:1220 """Called before the request is dispatched. Calls1221 :attr:`url_value_preprocessors` registered with the app and the1222 current blueprint (if any). Then calls :attr:`before_request_funcs`256 unmodified linesmodified:src/flask/blueprints.py+58 added-593 removed
1 from __future__ import annotations2 3 import os4 import typing as t5-from collections import defaultdict6-from functools import update_wrapper5+from datetime import timedelta6 8-from . import typing as ft9-from .scaffold import _endpoint_from_view_func10-from .scaffold import _sentinel11-from .scaffold import Scaffold12-from .scaffold import setupmethod7+from .globals import current_app8+from .helpers import send_from_directory9+from .sansio.blueprints import Blueprint as SansioBlueprint10+from .sansio.blueprints import BlueprintSetupState as BlueprintSetupState # noqa11 12 if t.TYPE_CHECKING: # pragma: no cover15- from .app import Flask13+ from .wrappers import Response14 17-DeferredSetupFunction = t.Callable[["BlueprintSetupState"], t.Callable]18-T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable)19-T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable)20-T_error_handler = t.TypeVar("T_error_handler", bound=ft.ErrorHandlerCallable)21-T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)22-T_template_context_processor = t.TypeVar(23- "T_template_context_processor", bound=ft.TemplateContextProcessorCallable24-)25-T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable)26-T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable)27-T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable)28-T_url_defaults = t.TypeVar("T_url_defaults", bound=ft.URLDefaultCallable)29-T_url_value_preprocessor = t.TypeVar(30- "T_url_value_preprocessor", bound=ft.URLValuePreprocessorCallable31-)15 16+class Blueprint(SansioBlueprint):17+ def get_send_file_max_age(self, filename: str | None) -> int | None:18+ """Used by :func:`send_file` to determine the ``max_age`` cache19+ value for a given file path if it wasn't passed.20 34-class BlueprintSetupState:35- """Temporary holder object for registering a blueprint with the36- application. An instance of this class is created by the37- :meth:`~flask.Blueprint.make_setup_state` method and later passed38- to all register callback functions.39- """21+ By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from22+ the configuration of :data:`~flask.current_app`. This defaults23+ to ``None``, which tells the browser to use conditional requests24+ instead of a timed cache, which is usually preferable.25 41- def __init__(42- self,43- blueprint: Blueprint,44- app: Flask,45- options: t.Any,46- first_registration: bool,47- ) -> None:48- #: a reference to the current application49- self.app = app26+ Note this is a duplicate of the same method in the Flask27+ class.28 51- #: a reference to the blueprint that created this setup state.52- self.blueprint = blueprint29+ .. versionchanged:: 2.030+ The default configuration is ``None`` instead of 12 hours.31 54- #: a dictionary with all options that were passed to the55- #: :meth:`~flask.Flask.register_blueprint` method.56- self.options = options57-58- #: as blueprints can be registered multiple times with the59- #: application and not everything wants to be registered60- #: multiple times on it, this attribute can be used to figure61- #: out if the blueprint was registered in the past already.62- self.first_registration = first_registration63-64- subdomain = self.options.get("subdomain")65- if subdomain is None:66- subdomain = self.blueprint.subdomain67-68- #: The subdomain that the blueprint should be active for, ``None``69- #: otherwise.70- self.subdomain = subdomain71-72- url_prefix = self.options.get("url_prefix")73- if url_prefix is None:74- url_prefix = self.blueprint.url_prefix75- #: The prefix that should be used for all URLs defined on the76- #: blueprint.77- self.url_prefix = url_prefix78-79- self.name = self.options.get("name", blueprint.name)80- self.name_prefix = self.options.get("name_prefix", "")81-82- #: A dictionary with URL defaults that is added to each and every83- #: URL that was defined with the blueprint.84- self.url_defaults = dict(self.blueprint.url_values_defaults)85- self.url_defaults.update(self.options.get("url_defaults", ()))86-87- def add_url_rule(88- self,89- rule: str,90- endpoint: str | None = None,91- view_func: t.Callable | None = None,92- **options: t.Any,93- ) -> None:94- """A helper method to register a rule (and optionally a view function)95- to the application. The endpoint is automatically prefixed with the96- blueprint's name.32+ .. versionadded:: 0.933 """98- if self.url_prefix is not None:99- if rule:100- rule = "/".join((self.url_prefix.rstrip("/"), rule.lstrip("/")))101- else:102- rule = self.url_prefix103- options.setdefault("subdomain", self.subdomain)104- if endpoint is None:105- endpoint = _endpoint_from_view_func(view_func) # type: ignore106- defaults = self.url_defaults107- if "defaults" in options:108- defaults = dict(defaults, **options.pop("defaults"))34+ value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]35 110- self.app.add_url_rule(111- rule,112- f"{self.name_prefix}.{self.name}.{endpoint}".lstrip("."),113- view_func,114- defaults=defaults,115- **options,116- )36+ if value is None:37+ return None38 39+ if isinstance(value, timedelta):40+ return int(value.total_seconds())41 119-class Blueprint(Scaffold):120- """Represents a blueprint, a collection of routes and other121- app-related functions that can be registered on a real application122- later.42+ return value43 124- A blueprint is an object that allows defining application functions125- without requiring an application object ahead of time. It uses the126- same decorators as :class:`~flask.Flask`, but defers the need for an127- application by recording them for later registration.44+ def send_static_file(self, filename: str) -> Response:45+ """The view function used to serve files from46+ :attr:`static_folder`. A route is automatically registered for47+ this view at :attr:`static_url_path` if :attr:`static_folder` is48+ set.49 129- Decorating a function with a blueprint creates a deferred function130- that is called with :class:`~flask.blueprints.BlueprintSetupState`131- when the blueprint is registered on an application.50+ Note this is a duplicate of the same method in the Flask51+ class.52 133- See :doc:`/blueprints` for more information.53+ .. versionadded:: 0.554 135- :param name: The name of the blueprint. Will be prepended to each136- endpoint name.137- :param import_name: The name of the blueprint package, usually138- ``__name__``. This helps locate the ``root_path`` for the139- blueprint.140- :param static_folder: A folder with static files that should be141- served by the blueprint's static route. The path is relative to142- the blueprint's root path. Blueprint static files are disabled143- by default.144- :param static_url_path: The url to serve static files from.145- Defaults to ``static_folder``. If the blueprint does not have146- a ``url_prefix``, the app's static route will take precedence,147- and the blueprint's static files won't be accessible.148- :param template_folder: A folder with templates that should be added149- to the app's template search path. The path is relative to the150- blueprint's root path. Blueprint templates are disabled by151- default. Blueprint templates have a lower precedence than those152- in the app's templates folder.153- :param url_prefix: A path to prepend to all of the blueprint's URLs,154- to make them distinct from the rest of the app's routes.155- :param subdomain: A subdomain that blueprint routes will match on by156- default.157- :param url_defaults: A dict of default values that blueprint routes158- will receive by default.159- :param root_path: By default, the blueprint will automatically set160- this based on ``import_name``. In certain situations this161- automatic detection can fail, so the path can be specified162- manually instead.163-164- .. versionchanged:: 1.1.0165- Blueprints have a ``cli`` group to register nested CLI commands.166- The ``cli_group`` parameter controls the name of the group under167- the ``flask`` command.168-169- .. versionadded:: 0.7170- """171-172- _got_registered_once = False173-174- def __init__(175- self,176- name: str,177- import_name: str,178- static_folder: str | os.PathLike | None = None,179- static_url_path: str | None = None,180- template_folder: str | os.PathLike | None = None,181- url_prefix: str | None = None,182- subdomain: str | None = None,183- url_defaults: dict | None = None,184- root_path: str | None = None,185- cli_group: str | None = _sentinel, # type: ignore186- ):187- super().__init__(188- import_name=import_name,189- static_folder=static_folder,190- static_url_path=static_url_path,191- template_folder=template_folder,192- root_path=root_path,193- )194-195- if not name:196- raise ValueError("'name' may not be empty.")197-198- if "." in name:199- raise ValueError("'name' may not contain a dot '.' character.")200-201- self.name = name202- self.url_prefix = url_prefix203- self.subdomain = subdomain204- self.deferred_functions: list[DeferredSetupFunction] = []205-206- if url_defaults is None:207- url_defaults = {}208-209- self.url_values_defaults = url_defaults210- self.cli_group = cli_group211- self._blueprints: list[tuple[Blueprint, dict]] = []212-213- def _check_setup_finished(self, f_name: str) -> None:214- if self._got_registered_once:215- raise AssertionError(216- f"The setup method '{f_name}' can no longer be called on the blueprint"217- f" '{self.name}'. It has already been registered at least once, any"218- " changes will not be applied consistently.\n"219- "Make sure all imports, decorators, functions, etc. needed to set up"220- " the blueprint are done before registering it."221- )222-223- @setupmethod224- def record(self, func: t.Callable) -> None:225- """Registers a function that is called when the blueprint is226- registered on the application. This function is called with the227- state as argument as returned by the :meth:`make_setup_state`228- method.55 """230- self.deferred_functions.append(func)56+ if not self.has_static_folder:57+ raise RuntimeError("'static_folder' must be set to serve static_files.")58 232- @setupmethod233- def record_once(self, func: t.Callable) -> None:234- """Works like :meth:`record` but wraps the function in another235- function that will ensure the function is only called once. If the236- blueprint is registered a second time on the application, the237- function passed is not called.238- """239-240- def wrapper(state: BlueprintSetupState) -> None:241- if state.first_registration:242- func(state)243-244- self.record(update_wrapper(wrapper, func))245-246- def make_setup_state(247- self, app: Flask, options: dict, first_registration: bool = False248- ) -> BlueprintSetupState:249- """Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`250- object that is later passed to the register callback functions.251- Subclasses can override this to return a subclass of the setup state.252- """253- return BlueprintSetupState(self, app, options, first_registration)254-255- @setupmethod256- def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:257- """Register a :class:`~flask.Blueprint` on this blueprint. Keyword258- arguments passed to this method will override the defaults set259- on the blueprint.260-261- .. versionchanged:: 2.0.1262- The ``name`` option can be used to change the (pre-dotted)263- name the blueprint is registered with. This allows the same264- blueprint to be registered multiple times with unique names265- for ``url_for``.266-267- .. versionadded:: 2.0268- """269- if blueprint is self:270- raise ValueError("Cannot register a blueprint on itself")271- self._blueprints.append((blueprint, options))272-273- def register(self, app: Flask, options: dict) -> None:274- """Called by :meth:`Flask.register_blueprint` to register all275- views and callbacks registered on the blueprint with the276- application. Creates a :class:`.BlueprintSetupState` and calls277- each :meth:`record` callback with it.278-279- :param app: The application this blueprint is being registered280- with.281- :param options: Keyword arguments forwarded from282- :meth:`~Flask.register_blueprint`.283-284- .. versionchanged:: 2.3285- Nested blueprints now correctly apply subdomains.286-287- .. versionchanged:: 2.1288- Registering the same blueprint with the same name multiple289- times is an error.290-291- .. versionchanged:: 2.0.1292- Nested blueprints are registered with their dotted name.293- This allows different blueprints with the same name to be294- nested at different locations.295-296- .. versionchanged:: 2.0.1297- The ``name`` option can be used to change the (pre-dotted)298- name the blueprint is registered with. This allows the same299- blueprint to be registered multiple times with unique names300- for ``url_for``.301- """302- name_prefix = options.get("name_prefix", "")303- self_name = options.get("name", self.name)304- name = f"{name_prefix}.{self_name}".lstrip(".")305-306- if name in app.blueprints:307- bp_desc = "this" if app.blueprints[name] is self else "a different"308- existing_at = f" '{name}'" if self_name != name else ""309-310- raise ValueError(311- f"The name '{self_name}' is already registered for"312- f" {bp_desc} blueprint{existing_at}. Use 'name=' to"313- f" provide a unique name."314- )315-316- first_bp_registration = not any(bp is self for bp in app.blueprints.values())317- first_name_registration = name not in app.blueprints318-319- app.blueprints[name] = self320- self._got_registered_once = True321- state = self.make_setup_state(app, options, first_bp_registration)322-323- if self.has_static_folder:324- state.add_url_rule(325- f"{self.static_url_path}/<path:filename>",326- view_func=self.send_static_file,327- endpoint="static",328- )329-330- # Merge blueprint data into parent.331- if first_bp_registration or first_name_registration:332-333- def extend(bp_dict, parent_dict):334- for key, values in bp_dict.items():335- key = name if key is None else f"{name}.{key}"336- parent_dict[key].extend(values)337-338- for key, value in self.error_handler_spec.items():339- key = name if key is None else f"{name}.{key}"340- value = defaultdict(341- dict,342- {343- code: {344- exc_class: func for exc_class, func in code_values.items()345- }346- for code, code_values in value.items()347- },348- )349- app.error_handler_spec[key] = value350-351- for endpoint, func in self.view_functions.items():352- app.view_functions[endpoint] = func353-354- extend(self.before_request_funcs, app.before_request_funcs)355- extend(self.after_request_funcs, app.after_request_funcs)356- extend(357- self.teardown_request_funcs,358- app.teardown_request_funcs,359- )360- extend(self.url_default_functions, app.url_default_functions)361- extend(self.url_value_preprocessors, app.url_value_preprocessors)362- extend(self.template_context_processors, app.template_context_processors)363-364- for deferred in self.deferred_functions:365- deferred(state)366-367- cli_resolved_group = options.get("cli_group", self.cli_group)368-369- if self.cli.commands:370- if cli_resolved_group is None:371- app.cli.commands.update(self.cli.commands)372- elif cli_resolved_group is _sentinel:373- self.cli.name = name374- app.cli.add_command(self.cli)375- else:376- self.cli.name = cli_resolved_group377- app.cli.add_command(self.cli)378-379- for blueprint, bp_options in self._blueprints:380- bp_options = bp_options.copy()381- bp_url_prefix = bp_options.get("url_prefix")382- bp_subdomain = bp_options.get("subdomain")383-384- if bp_subdomain is None:385- bp_subdomain = blueprint.subdomain386-387- if state.subdomain is not None and bp_subdomain is not None:388- bp_options["subdomain"] = bp_subdomain + "." + state.subdomain389- elif bp_subdomain is not None:390- bp_options["subdomain"] = bp_subdomain391- elif state.subdomain is not None:392- bp_options["subdomain"] = state.subdomain393-394- if bp_url_prefix is None:395- bp_url_prefix = blueprint.url_prefix396-397- if state.url_prefix is not None and bp_url_prefix is not None:398- bp_options["url_prefix"] = (399- state.url_prefix.rstrip("/") + "/" + bp_url_prefix.lstrip("/")400- )401- elif bp_url_prefix is not None:402- bp_options["url_prefix"] = bp_url_prefix403- elif state.url_prefix is not None:404- bp_options["url_prefix"] = state.url_prefix405-406- bp_options["name_prefix"] = name407- blueprint.register(app, bp_options)408-409- @setupmethod410- def add_url_rule(411- self,412- rule: str,413- endpoint: str | None = None,414- view_func: ft.RouteCallable | None = None,415- provide_automatic_options: bool | None = None,416- **options: t.Any,417- ) -> None:418- """Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for419- full documentation.420-421- The URL rule is prefixed with the blueprint's URL prefix. The endpoint name,422- used with :func:`url_for`, is prefixed with the blueprint's name.423- """424- if endpoint and "." in endpoint:425- raise ValueError("'endpoint' may not contain a dot '.' character.")426-427- if view_func and hasattr(view_func, "__name__") and "." in view_func.__name__:428- raise ValueError("'view_func' name may not contain a dot '.' character.")429-430- self.record(431- lambda s: s.add_url_rule(432- rule,433- endpoint,434- view_func,435- provide_automatic_options=provide_automatic_options,436- **options,437- )59+ # send_file only knows to call get_send_file_max_age on the app,60+ # call it here so it works for blueprints too.61+ max_age = self.get_send_file_max_age(filename)62+ return send_from_directory(63+ t.cast(str, self.static_folder), filename, max_age=max_age64 )65 440- @setupmethod441- def app_template_filter(442- self, name: str | None = None443- ) -> t.Callable[[T_template_filter], T_template_filter]:444- """Register a template filter, available in any template rendered by the445- application. Equivalent to :meth:`.Flask.template_filter`.66+ def open_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:67+ """Open a resource file relative to :attr:`root_path` for68+ reading.69 447- :param name: the optional name of the filter, otherwise the448- function name will be used.449- """70+ For example, if the file ``schema.sql`` is next to the file71+ ``app.py`` where the ``Flask`` app is defined, it can be opened72+ with:73 451- def decorator(f: T_template_filter) -> T_template_filter:452- self.add_app_template_filter(f, name=name)453- return f74+ .. code-block:: python75 455- return decorator76+ with app.open_resource("schema.sql") as f:77+ conn.executescript(f.read())78 457- @setupmethod458- def add_app_template_filter(459- self, f: ft.TemplateFilterCallable, name: str | None = None460- ) -> None:461- """Register a template filter, available in any template rendered by the462- application. Works like the :meth:`app_template_filter` decorator. Equivalent to463- :meth:`.Flask.add_template_filter`.79+ :param resource: Path to the resource relative to80+ :attr:`root_path`.81+ :param mode: Open the file in this mode. Only reading is82+ supported, valid values are "r" (or "rt") and "rb".83 465- :param name: the optional name of the filter, otherwise the466- function name will be used.467- """84+ Note this is a duplicate of the same method in the Flask85+ class.86 469- def register_template(state: BlueprintSetupState) -> None:470- state.app.jinja_env.filters[name or f.__name__] = f471-472- self.record_once(register_template)473-474- @setupmethod475- def app_template_test(476- self, name: str | None = None477- ) -> t.Callable[[T_template_test], T_template_test]:478- """Register a template test, available in any template rendered by the479- application. Equivalent to :meth:`.Flask.template_test`.480-481- .. versionadded:: 0.10482-483- :param name: the optional name of the test, otherwise the484- function name will be used.87 """88+ if mode not in {"r", "rt", "rb"}:89+ raise ValueError("Resources can only be opened for reading.")90 487- def decorator(f: T_template_test) -> T_template_test:488- self.add_app_template_test(f, name=name)489- return f490-491- return decorator492-493- @setupmethod494- def add_app_template_test(495- self, f: ft.TemplateTestCallable, name: str | None = None496- ) -> None:497- """Register a template test, available in any template rendered by the498- application. Works like the :meth:`app_template_test` decorator. Equivalent to499- :meth:`.Flask.add_template_test`.500-501- .. versionadded:: 0.10502-503- :param name: the optional name of the test, otherwise the504- function name will be used.505- """506-507- def register_template(state: BlueprintSetupState) -> None:508- state.app.jinja_env.tests[name or f.__name__] = f509-510- self.record_once(register_template)511-512- @setupmethod513- def app_template_global(514- self, name: str | None = None515- ) -> t.Callable[[T_template_global], T_template_global]:516- """Register a template global, available in any template rendered by the517- application. Equivalent to :meth:`.Flask.template_global`.518-519- .. versionadded:: 0.10520-521- :param name: the optional name of the global, otherwise the522- function name will be used.523- """524-525- def decorator(f: T_template_global) -> T_template_global:526- self.add_app_template_global(f, name=name)527- return f528-529- return decorator530-531- @setupmethod532- def add_app_template_global(533- self, f: ft.TemplateGlobalCallable, name: str | None = None534- ) -> None:535- """Register a template global, available in any template rendered by the536- application. Works like the :meth:`app_template_global` decorator. Equivalent to537- :meth:`.Flask.add_template_global`.538-539- .. versionadded:: 0.10540-541- :param name: the optional name of the global, otherwise the542- function name will be used.543- """544-545- def register_template(state: BlueprintSetupState) -> None:546- state.app.jinja_env.globals[name or f.__name__] = f547-548- self.record_once(register_template)549-550- @setupmethod551- def before_app_request(self, f: T_before_request) -> T_before_request:552- """Like :meth:`before_request`, but before every request, not only those handled553- by the blueprint. Equivalent to :meth:`.Flask.before_request`.554- """555- self.record_once(556- lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)557- )558- return f559-560- @setupmethod561- def after_app_request(self, f: T_after_request) -> T_after_request:562- """Like :meth:`after_request`, but after every request, not only those handled563- by the blueprint. Equivalent to :meth:`.Flask.after_request`.564- """565- self.record_once(566- lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)567- )568- return f569-570- @setupmethod571- def teardown_app_request(self, f: T_teardown) -> T_teardown:572- """Like :meth:`teardown_request`, but after every request, not only those573- handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`.574- """575- self.record_once(576- lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)577- )578- return f579-580- @setupmethod581- def app_context_processor(582- self, f: T_template_context_processor583- ) -> T_template_context_processor:584- """Like :meth:`context_processor`, but for templates rendered by every view, not585- only by the blueprint. Equivalent to :meth:`.Flask.context_processor`.586- """587- self.record_once(588- lambda s: s.app.template_context_processors.setdefault(None, []).append(f)589- )590- return f591-592- @setupmethod593- def app_errorhandler(594- self, code: type[Exception] | int595- ) -> t.Callable[[T_error_handler], T_error_handler]:596- """Like :meth:`errorhandler`, but for every request, not only those handled by597- the blueprint. Equivalent to :meth:`.Flask.errorhandler`.598- """599-600- def decorator(f: T_error_handler) -> T_error_handler:601- self.record_once(lambda s: s.app.errorhandler(code)(f))602- return f603-604- return decorator605-606- @setupmethod607- def app_url_value_preprocessor(608- self, f: T_url_value_preprocessor609- ) -> T_url_value_preprocessor:610- """Like :meth:`url_value_preprocessor`, but for every request, not only those611- handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`.612- """613- self.record_once(614- lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)615- )616- return f617-618- @setupmethod619- def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults:620- """Like :meth:`url_defaults`, but for every request, not only those handled by621- the blueprint. Equivalent to :meth:`.Flask.url_defaults`.622- """623- self.record_once(624- lambda s: s.app.url_default_functions.setdefault(None, []).append(f)625- )626- return f91+ return open(os.path.join(self.root_path, resource), mode)modified:src/flask/debughelpers.py+3 added-3 removed
1 from __future__ import annotations2 3 import typing as t4 5-from .app import Flask5 from .blueprints import Blueprint6 from .globals import request_ctx7+from .sansio.app import App8 9 10 class UnexpectedUnicodeError(AssertionError, UnicodeError):11 """Raised in places where we want some better error reporting for100 unmodified lines112 continue113 yield f"{key}: {value!r}"114 115 116-def explain_template_loading_attempts(app: Flask, template, attempts) -> None:116+def explain_template_loading_attempts(app: App, template, attempts) -> None:117 """This should help developers understand what failed"""118 info = [f"Locating template {template!r}:"]119 total_found = 0120 blueprint = None121 if request_ctx and request_ctx.request.blueprint is not None:122 blueprint = request_ctx.request.blueprint123 124 for idx, (loader, srcobj, triple) in enumerate(attempts):125- if isinstance(srcobj, Flask):125+ if isinstance(srcobj, App):126 src_info = f"application {srcobj.import_name!r}"127 elif isinstance(srcobj, Blueprint):128 src_info = f"blueprint {srcobj.name!r} ({srcobj.import_name})"129 else:31 unmodified linesmodified:src/flask/logging.py+2 added-2 removed
7 unmodified lines8 9 from .globals import request10 11 if t.TYPE_CHECKING: # pragma: no cover12- from .app import Flask12+ from .sansio.app import App13 14 15 @LocalProxy16 def wsgi_errors_stream() -> t.TextIO:34 unmodified lines51 logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")52 )53 54 55-def create_logger(app: Flask) -> logging.Logger:55+def create_logger(app: App) -> logging.Logger:56 """Get the Flask app's logger and configure it if needed.57 58 The logger name will be the same as59 :attr:`app.import_name <flask.Flask.name>`.17 unmodified linesdeleted:src/flask/scaffold.py-873 removed
1-from __future__ import annotations2-3-import importlib.util4-import os5-import pathlib6-import sys7-import typing as t8-from collections import defaultdict9-from datetime import timedelta10-from functools import update_wrapper11-12-from jinja2 import FileSystemLoader13-from werkzeug.exceptions import default_exceptions14-from werkzeug.exceptions import HTTPException15-from werkzeug.utils import cached_property16-17-from . import typing as ft18-from .cli import AppGroup19-from .globals import current_app20-from .helpers import get_root_path21-from .helpers import send_from_directory22-from .templating import _default_template_ctx_processor23-24-if t.TYPE_CHECKING: # pragma: no cover25- from .wrappers import Response26-27-# a singleton sentinel value for parameter defaults28-_sentinel = object()29-30-F = t.TypeVar("F", bound=t.Callable[..., t.Any])31-T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable)32-T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable)33-T_error_handler = t.TypeVar("T_error_handler", bound=ft.ErrorHandlerCallable)34-T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)35-T_template_context_processor = t.TypeVar(36- "T_template_context_processor", bound=ft.TemplateContextProcessorCallable37-)38-T_url_defaults = t.TypeVar("T_url_defaults", bound=ft.URLDefaultCallable)39-T_url_value_preprocessor = t.TypeVar(40- "T_url_value_preprocessor", bound=ft.URLValuePreprocessorCallable41-)42-T_route = t.TypeVar("T_route", bound=ft.RouteCallable)43-44-45-def setupmethod(f: F) -> F:46- f_name = f.__name__47-48- def wrapper_func(self, *args: t.Any, **kwargs: t.Any) -> t.Any:49- self._check_setup_finished(f_name)50- return f(self, *args, **kwargs)51-52- return t.cast(F, update_wrapper(wrapper_func, f))53-54-55-class Scaffold:56- """Common behavior shared between :class:`~flask.Flask` and57- :class:`~flask.blueprints.Blueprint`.58-59- :param import_name: The import name of the module where this object60- is defined. Usually :attr:`__name__` should be used.61- :param static_folder: Path to a folder of static files to serve.62- If this is set, a static route will be added.63- :param static_url_path: URL prefix for the static route.64- :param template_folder: Path to a folder containing template files.65- for rendering. If this is set, a Jinja loader will be added.66- :param root_path: The path that static, template, and resource files67- are relative to. Typically not set, it is discovered based on68- the ``import_name``.69-70- .. versionadded:: 2.071- """72-73- name: str74- _static_folder: str | None = None75- _static_url_path: str | None = None76-77- def __init__(78- self,79- import_name: str,80- static_folder: str | os.PathLike | None = None,81- static_url_path: str | None = None,82- template_folder: str | os.PathLike | None = None,83- root_path: str | None = None,84- ):85- #: The name of the package or module that this object belongs86- #: to. Do not change this once it is set by the constructor.87- self.import_name = import_name88-89- self.static_folder = static_folder # type: ignore90- self.static_url_path = static_url_path91-92- #: The path to the templates folder, relative to93- #: :attr:`root_path`, to add to the template loader. ``None`` if94- #: templates should not be added.95- self.template_folder = template_folder96-97- if root_path is None:98- root_path = get_root_path(self.import_name)99-100- #: Absolute path to the package on the filesystem. Used to look101- #: up resources contained in the package.102- self.root_path = root_path103-104- #: The Click command group for registering CLI commands for this105- #: object. The commands are available from the ``flask`` command106- #: once the application has been discovered and blueprints have107- #: been registered.108- self.cli = AppGroup()109-110- #: A dictionary mapping endpoint names to view functions.111- #:112- #: To register a view function, use the :meth:`route` decorator.113- #:114- #: This data structure is internal. It should not be modified115- #: directly and its format may change at any time.116- self.view_functions: dict[str, t.Callable] = {}117-118- #: A data structure of registered error handlers, in the format119- #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is120- #: the name of a blueprint the handlers are active for, or121- #: ``None`` for all requests. The ``code`` key is the HTTP122- #: status code for ``HTTPException``, or ``None`` for123- #: other exceptions. The innermost dictionary maps exception124- #: classes to handler functions.125- #:126- #: To register an error handler, use the :meth:`errorhandler`127- #: decorator.128- #:129- #: This data structure is internal. It should not be modified130- #: directly and its format may change at any time.131- self.error_handler_spec: dict[132- ft.AppOrBlueprintKey,133- dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]],134- ] = defaultdict(lambda: defaultdict(dict))135-136- #: A data structure of functions to call at the beginning of137- #: each request, in the format ``{scope: [functions]}``. The138- #: ``scope`` key is the name of a blueprint the functions are139- #: active for, or ``None`` for all requests.140- #:141- #: To register a function, use the :meth:`before_request`142- #: decorator.143- #:144- #: This data structure is internal. It should not be modified145- #: directly and its format may change at any time.146- self.before_request_funcs: dict[147- ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]148- ] = defaultdict(list)149-150- #: A data structure of functions to call at the end of each151- #: request, in the format ``{scope: [functions]}``. The152- #: ``scope`` key is the name of a blueprint the functions are153- #: active for, or ``None`` for all requests.154- #:155- #: To register a function, use the :meth:`after_request`156- #: decorator.157- #:158- #: This data structure is internal. It should not be modified159- #: directly and its format may change at any time.160- self.after_request_funcs: dict[161- ft.AppOrBlueprintKey, list[ft.AfterRequestCallable]162- ] = defaultdict(list)163-164- #: A data structure of functions to call at the end of each165- #: request even if an exception is raised, in the format166- #: ``{scope: [functions]}``. The ``scope`` key is the name of a167- #: blueprint the functions are active for, or ``None`` for all168- #: requests.169- #:170- #: To register a function, use the :meth:`teardown_request`171- #: decorator.172- #:173- #: This data structure is internal. It should not be modified174- #: directly and its format may change at any time.175- self.teardown_request_funcs: dict[176- ft.AppOrBlueprintKey, list[ft.TeardownCallable]177- ] = defaultdict(list)178-179- #: A data structure of functions to call to pass extra context180- #: values when rendering templates, in the format181- #: ``{scope: [functions]}``. The ``scope`` key is the name of a182- #: blueprint the functions are active for, or ``None`` for all183- #: requests.184- #:185- #: To register a function, use the :meth:`context_processor`186- #: decorator.187- #:188- #: This data structure is internal. It should not be modified189- #: directly and its format may change at any time.190- self.template_context_processors: dict[191- ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]192- ] = defaultdict(list, {None: [_default_template_ctx_processor]})193-194- #: A data structure of functions to call to modify the keyword195- #: arguments passed to the view function, in the format196- #: ``{scope: [functions]}``. The ``scope`` key is the name of a197- #: blueprint the functions are active for, or ``None`` for all198- #: requests.199- #:200- #: To register a function, use the201- #: :meth:`url_value_preprocessor` decorator.202- #:203- #: This data structure is internal. It should not be modified204- #: directly and its format may change at any time.205- self.url_value_preprocessors: dict[206- ft.AppOrBlueprintKey,207- list[ft.URLValuePreprocessorCallable],208- ] = defaultdict(list)209-210- #: A data structure of functions to call to modify the keyword211- #: arguments when generating URLs, in the format212- #: ``{scope: [functions]}``. The ``scope`` key is the name of a213- #: blueprint the functions are active for, or ``None`` for all214- #: requests.215- #:216- #: To register a function, use the :meth:`url_defaults`217- #: decorator.218- #:219- #: This data structure is internal. It should not be modified220- #: directly and its format may change at any time.221- self.url_default_functions: dict[222- ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]223- ] = defaultdict(list)224-225- def __repr__(self) -> str:226- return f"<{type(self).__name__} {self.name!r}>"227-228- def _check_setup_finished(self, f_name: str) -> None:229- raise NotImplementedError230-231- @property232- def static_folder(self) -> str | None:233- """The absolute path to the configured static folder. ``None``234- if no static folder is set.235- """236- if self._static_folder is not None:237- return os.path.join(self.root_path, self._static_folder)238- else:239- return None240-241- @static_folder.setter242- def static_folder(self, value: str | os.PathLike | None) -> None:243- if value is not None:244- value = os.fspath(value).rstrip(r"\/")245-246- self._static_folder = value247-248- @property249- def has_static_folder(self) -> bool:250- """``True`` if :attr:`static_folder` is set.251-252- .. versionadded:: 0.5253- """254- return self.static_folder is not None255-256- @property257- def static_url_path(self) -> str | None:258- """The URL prefix that the static route will be accessible from.259-260- If it was not configured during init, it is derived from261- :attr:`static_folder`.262- """263- if self._static_url_path is not None:264- return self._static_url_path265-266- if self.static_folder is not None:267- basename = os.path.basename(self.static_folder)268- return f"/{basename}".rstrip("/")269-270- return None271-272- @static_url_path.setter273- def static_url_path(self, value: str | None) -> None:274- if value is not None:275- value = value.rstrip("/")276-277- self._static_url_path = value278-279- def get_send_file_max_age(self, filename: str | None) -> int | None:280- """Used by :func:`send_file` to determine the ``max_age`` cache281- value for a given file path if it wasn't passed.282-283- By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from284- the configuration of :data:`~flask.current_app`. This defaults285- to ``None``, which tells the browser to use conditional requests286- instead of a timed cache, which is usually preferable.287-288- .. versionchanged:: 2.0289- The default configuration is ``None`` instead of 12 hours.290-291- .. versionadded:: 0.9292- """293- value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]294-295- if value is None:296- return None297-298- if isinstance(value, timedelta):299- return int(value.total_seconds())300-301- return value302-303- def send_static_file(self, filename: str) -> Response:304- """The view function used to serve files from305- :attr:`static_folder`. A route is automatically registered for306- this view at :attr:`static_url_path` if :attr:`static_folder` is307- set.308-309- .. versionadded:: 0.5310- """311- if not self.has_static_folder:312- raise RuntimeError("'static_folder' must be set to serve static_files.")313-314- # send_file only knows to call get_send_file_max_age on the app,315- # call it here so it works for blueprints too.316- max_age = self.get_send_file_max_age(filename)317- return send_from_directory(318- t.cast(str, self.static_folder), filename, max_age=max_age319- )320-321- @cached_property322- def jinja_loader(self) -> FileSystemLoader | None:323- """The Jinja loader for this object's templates. By default this324- is a class :class:`jinja2.loaders.FileSystemLoader` to325- :attr:`template_folder` if it is set.326-327- .. versionadded:: 0.5328- """329- if self.template_folder is not None:330- return FileSystemLoader(os.path.join(self.root_path, self.template_folder))331- else:332- return None333-334- def open_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:335- """Open a resource file relative to :attr:`root_path` for336- reading.337-338- For example, if the file ``schema.sql`` is next to the file339- ``app.py`` where the ``Flask`` app is defined, it can be opened340- with:341-342- .. code-block:: python343-344- with app.open_resource("schema.sql") as f:345- conn.executescript(f.read())346-347- :param resource: Path to the resource relative to348- :attr:`root_path`.349- :param mode: Open the file in this mode. Only reading is350- supported, valid values are "r" (or "rt") and "rb".351- """352- if mode not in {"r", "rt", "rb"}:353- raise ValueError("Resources can only be opened for reading.")354-355- return open(os.path.join(self.root_path, resource), mode)356-357- def _method_route(358- self,359- method: str,360- rule: str,361- options: dict,362- ) -> t.Callable[[T_route], T_route]:363- if "methods" in options:364- raise TypeError("Use the 'route' decorator to use the 'methods' argument.")365-366- return self.route(rule, methods=[method], **options)367-368- @setupmethod369- def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:370- """Shortcut for :meth:`route` with ``methods=["GET"]``.371-372- .. versionadded:: 2.0373- """374- return self._method_route("GET", rule, options)375-376- @setupmethod377- def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:378- """Shortcut for :meth:`route` with ``methods=["POST"]``.379-380- .. versionadded:: 2.0381- """382- return self._method_route("POST", rule, options)383-384- @setupmethod385- def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:386- """Shortcut for :meth:`route` with ``methods=["PUT"]``.387-388- .. versionadded:: 2.0389- """390- return self._method_route("PUT", rule, options)391-392- @setupmethod393- def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:394- """Shortcut for :meth:`route` with ``methods=["DELETE"]``.395-396- .. versionadded:: 2.0397- """398- return self._method_route("DELETE", rule, options)399-400- @setupmethod401- def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:402- """Shortcut for :meth:`route` with ``methods=["PATCH"]``.403-404- .. versionadded:: 2.0405- """406- return self._method_route("PATCH", rule, options)407-408- @setupmethod409- def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:410- """Decorate a view function to register it with the given URL411- rule and options. Calls :meth:`add_url_rule`, which has more412- details about the implementation.413-414- .. code-block:: python415-416- @app.route("/")417- def index():418- return "Hello, World!"419-420- See :ref:`url-route-registrations`.421-422- The endpoint name for the route defaults to the name of the view423- function if the ``endpoint`` parameter isn't passed.424-425- The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and426- ``OPTIONS`` are added automatically.427-428- :param rule: The URL rule string.429- :param options: Extra options passed to the430- :class:`~werkzeug.routing.Rule` object.431- """432-433- def decorator(f: T_route) -> T_route:434- endpoint = options.pop("endpoint", None)435- self.add_url_rule(rule, endpoint, f, **options)436- return f437-438- return decorator439-440- @setupmethod441- def add_url_rule(442- self,443- rule: str,444- endpoint: str | None = None,445- view_func: ft.RouteCallable | None = None,446- provide_automatic_options: bool | None = None,447- **options: t.Any,448- ) -> None:449- """Register a rule for routing incoming requests and building450- URLs. The :meth:`route` decorator is a shortcut to call this451- with the ``view_func`` argument. These are equivalent:452-453- .. code-block:: python454-455- @app.route("/")456- def index():457- ...458-459- .. code-block:: python460-461- def index():462- ...463-464- app.add_url_rule("/", view_func=index)465-466- See :ref:`url-route-registrations`.467-468- The endpoint name for the route defaults to the name of the view469- function if the ``endpoint`` parameter isn't passed. An error470- will be raised if a function has already been registered for the471- endpoint.472-473- The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` is474- always added automatically, and ``OPTIONS`` is added475- automatically by default.476-477- ``view_func`` does not necessarily need to be passed, but if the478- rule should participate in routing an endpoint name must be479- associated with a view function at some point with the480- :meth:`endpoint` decorator.481-482- .. code-block:: python483-484- app.add_url_rule("/", endpoint="index")485-486- @app.endpoint("index")487- def index():488- ...489-490- If ``view_func`` has a ``required_methods`` attribute, those491- methods are added to the passed and automatic methods. If it492- has a ``provide_automatic_methods`` attribute, it is used as the493- default if the parameter is not passed.494-495- :param rule: The URL rule string.496- :param endpoint: The endpoint name to associate with the rule497- and view function. Used when routing and building URLs.498- Defaults to ``view_func.__name__``.499- :param view_func: The view function to associate with the500- endpoint name.501- :param provide_automatic_options: Add the ``OPTIONS`` method and502- respond to ``OPTIONS`` requests automatically.503- :param options: Extra options passed to the504- :class:`~werkzeug.routing.Rule` object.505- """506- raise NotImplementedError507-508- @setupmethod509- def endpoint(self, endpoint: str) -> t.Callable[[F], F]:510- """Decorate a view function to register it for the given511- endpoint. Used if a rule is added without a ``view_func`` with512- :meth:`add_url_rule`.513-514- .. code-block:: python515-516- app.add_url_rule("/ex", endpoint="example")517-518- @app.endpoint("example")519- def example():520- ...521-522- :param endpoint: The endpoint name to associate with the view523- function.524- """525-526- def decorator(f: F) -> F:527- self.view_functions[endpoint] = f528- return f529-530- return decorator531-532- @setupmethod533- def before_request(self, f: T_before_request) -> T_before_request:534- """Register a function to run before each request.535-536- For example, this can be used to open a database connection, or537- to load the logged in user from the session.538-539- .. code-block:: python540-541- @app.before_request542- def load_user():543- if "user_id" in session:544- g.user = db.session.get(session["user_id"])545-546- The function will be called without any arguments. If it returns547- a non-``None`` value, the value is handled as if it was the548- return value from the view, and further request handling is549- stopped.550-551- This is available on both app and blueprint objects. When used on an app, this552- executes before every request. When used on a blueprint, this executes before553- every request that the blueprint handles. To register with a blueprint and554- execute before every request, use :meth:`.Blueprint.before_app_request`.555- """556- self.before_request_funcs.setdefault(None, []).append(f)557- return f558-559- @setupmethod560- def after_request(self, f: T_after_request) -> T_after_request:561- """Register a function to run after each request to this object.562-563- The function is called with the response object, and must return564- a response object. This allows the functions to modify or565- replace the response before it is sent.566-567- If a function raises an exception, any remaining568- ``after_request`` functions will not be called. Therefore, this569- should not be used for actions that must execute, such as to570- close resources. Use :meth:`teardown_request` for that.571-572- This is available on both app and blueprint objects. When used on an app, this573- executes after every request. When used on a blueprint, this executes after574- every request that the blueprint handles. To register with a blueprint and575- execute after every request, use :meth:`.Blueprint.after_app_request`.576- """577- self.after_request_funcs.setdefault(None, []).append(f)578- return f579-580- @setupmethod581- def teardown_request(self, f: T_teardown) -> T_teardown:582- """Register a function to be called when the request context is583- popped. Typically this happens at the end of each request, but584- contexts may be pushed manually as well during testing.585-586- .. code-block:: python587-588- with app.test_request_context():589- ...590-591- When the ``with`` block exits (or ``ctx.pop()`` is called), the592- teardown functions are called just before the request context is593- made inactive.594-595- When a teardown function was called because of an unhandled596- exception it will be passed an error object. If an597- :meth:`errorhandler` is registered, it will handle the exception598- and the teardown will not receive it.599-600- Teardown functions must avoid raising exceptions. If they601- execute code that might fail they must surround that code with a602- ``try``/``except`` block and log any errors.603-604- The return values of teardown functions are ignored.605-606- This is available on both app and blueprint objects. When used on an app, this607- executes after every request. When used on a blueprint, this executes after608- every request that the blueprint handles. To register with a blueprint and609- execute after every request, use :meth:`.Blueprint.teardown_app_request`.610- """611- self.teardown_request_funcs.setdefault(None, []).append(f)612- return f613-614- @setupmethod615- def context_processor(616- self,617- f: T_template_context_processor,618- ) -> T_template_context_processor:619- """Registers a template context processor function. These functions run before620- rendering a template. The keys of the returned dict are added as variables621- available in the template.622-623- This is available on both app and blueprint objects. When used on an app, this624- is called for every rendered template. When used on a blueprint, this is called625- for templates rendered from the blueprint's views. To register with a blueprint626- and affect every template, use :meth:`.Blueprint.app_context_processor`.627- """628- self.template_context_processors[None].append(f)629- return f630-631- @setupmethod632- def url_value_preprocessor(633- self,634- f: T_url_value_preprocessor,635- ) -> T_url_value_preprocessor:636- """Register a URL value preprocessor function for all view637- functions in the application. These functions will be called before the638- :meth:`before_request` functions.639-640- The function can modify the values captured from the matched url before641- they are passed to the view. For example, this can be used to pop a642- common language code value and place it in ``g`` rather than pass it to643- every view.644-645- The function is passed the endpoint name and values dict. The return646- value is ignored.647-648- This is available on both app and blueprint objects. When used on an app, this649- is called for every request. When used on a blueprint, this is called for650- requests that the blueprint handles. To register with a blueprint and affect651- every request, use :meth:`.Blueprint.app_url_value_preprocessor`.652- """653- self.url_value_preprocessors[None].append(f)654- return f655-656- @setupmethod657- def url_defaults(self, f: T_url_defaults) -> T_url_defaults:658- """Callback function for URL defaults for all view functions of the659- application. It's called with the endpoint and values and should660- update the values passed in place.661-662- This is available on both app and blueprint objects. When used on an app, this663- is called for every request. When used on a blueprint, this is called for664- requests that the blueprint handles. To register with a blueprint and affect665- every request, use :meth:`.Blueprint.app_url_defaults`.666- """667- self.url_default_functions[None].append(f)668- return f669-670- @setupmethod671- def errorhandler(672- self, code_or_exception: type[Exception] | int673- ) -> t.Callable[[T_error_handler], T_error_handler]:674- """Register a function to handle errors by code or exception class.675-676- A decorator that is used to register a function given an677- error code. Example::678-679- @app.errorhandler(404)680- def page_not_found(error):681- return 'This page does not exist', 404682-683- You can also register handlers for arbitrary exceptions::684-685- @app.errorhandler(DatabaseError)686- def special_exception_handler(error):687- return 'Database connection failed', 500688-689- This is available on both app and blueprint objects. When used on an app, this690- can handle errors from every request. When used on a blueprint, this can handle691- errors from requests that the blueprint handles. To register with a blueprint692- and affect every request, use :meth:`.Blueprint.app_errorhandler`.693-694- .. versionadded:: 0.7695- Use :meth:`register_error_handler` instead of modifying696- :attr:`error_handler_spec` directly, for application wide error697- handlers.698-699- .. versionadded:: 0.7700- One can now additionally also register custom exception types701- that do not necessarily have to be a subclass of the702- :class:`~werkzeug.exceptions.HTTPException` class.703-704- :param code_or_exception: the code as integer for the handler, or705- an arbitrary exception706- """707-708- def decorator(f: T_error_handler) -> T_error_handler:709- self.register_error_handler(code_or_exception, f)710- return f711-712- return decorator713-714- @setupmethod715- def register_error_handler(716- self,717- code_or_exception: type[Exception] | int,718- f: ft.ErrorHandlerCallable,719- ) -> None:720- """Alternative error attach function to the :meth:`errorhandler`721- decorator that is more straightforward to use for non decorator722- usage.723-724- .. versionadded:: 0.7725- """726- exc_class, code = self._get_exc_class_and_code(code_or_exception)727- self.error_handler_spec[None][code][exc_class] = f728-729- @staticmethod730- def _get_exc_class_and_code(731- exc_class_or_code: type[Exception] | int,732- ) -> tuple[type[Exception], int | None]:733- """Get the exception class being handled. For HTTP status codes734- or ``HTTPException`` subclasses, return both the exception and735- status code.736-737- :param exc_class_or_code: Any exception class, or an HTTP status738- code as an integer.739- """740- exc_class: type[Exception]741-742- if isinstance(exc_class_or_code, int):743- try:744- exc_class = default_exceptions[exc_class_or_code]745- except KeyError:746- raise ValueError(747- f"'{exc_class_or_code}' is not a recognized HTTP"748- " error code. Use a subclass of HTTPException with"749- " that code instead."750- ) from None751- else:752- exc_class = exc_class_or_code753-754- if isinstance(exc_class, Exception):755- raise TypeError(756- f"{exc_class!r} is an instance, not a class. Handlers"757- " can only be registered for Exception classes or HTTP"758- " error codes."759- )760-761- if not issubclass(exc_class, Exception):762- raise ValueError(763- f"'{exc_class.__name__}' is not a subclass of Exception."764- " Handlers can only be registered for Exception classes"765- " or HTTP error codes."766- )767-768- if issubclass(exc_class, HTTPException):769- return exc_class, exc_class.code770- else:771- return exc_class, None772-773-774-def _endpoint_from_view_func(view_func: t.Callable) -> str:775- """Internal helper that returns the default endpoint for a given776- function. This always is the function name.777- """778- assert view_func is not None, "expected view func if endpoint is not provided."779- return view_func.__name__780-781-782-def _path_is_relative_to(path: pathlib.PurePath, base: str) -> bool:783- # Path.is_relative_to doesn't exist until Python 3.9784- try:785- path.relative_to(base)786- return True787- except ValueError:788- return False789-790-791-def _find_package_path(import_name):792- """Find the path that contains the package or module."""793- root_mod_name, _, _ = import_name.partition(".")794-795- try:796- root_spec = importlib.util.find_spec(root_mod_name)797-798- if root_spec is None:799- raise ValueError("not found")800- except (ImportError, ValueError):801- # ImportError: the machinery told us it does not exist802- # ValueError:803- # - the module name was invalid804- # - the module name is __main__805- # - we raised `ValueError` due to `root_spec` being `None`806- return os.getcwd()807-808- if root_spec.origin in {"namespace", None}:809- # namespace package810- package_spec = importlib.util.find_spec(import_name)811-812- if package_spec is not None and package_spec.submodule_search_locations:813- # Pick the path in the namespace that contains the submodule.814- package_path = pathlib.Path(815- os.path.commonpath(package_spec.submodule_search_locations)816- )817- search_location = next(818- location819- for location in root_spec.submodule_search_locations820- if _path_is_relative_to(package_path, location)821- )822- else:823- # Pick the first path.824- search_location = root_spec.submodule_search_locations[0]825-826- return os.path.dirname(search_location)827- elif root_spec.submodule_search_locations:828- # package with __init__.py829- return os.path.dirname(os.path.dirname(root_spec.origin))830- else:831- # module832- return os.path.dirname(root_spec.origin)833-834-835-def find_package(import_name: str):836- """Find the prefix that a package is installed under, and the path837- that it would be imported from.838-839- The prefix is the directory containing the standard directory840- hierarchy (lib, bin, etc.). If the package is not installed to the841- system (:attr:`sys.prefix`) or a virtualenv (``site-packages``),842- ``None`` is returned.843-844- The path is the entry in :attr:`sys.path` that contains the package845- for import. If the package is not installed, it's assumed that the846- package was imported from the current working directory.847- """848- package_path = _find_package_path(import_name)849- py_prefix = os.path.abspath(sys.prefix)850-851- # installed to the system852- if _path_is_relative_to(pathlib.PurePath(package_path), py_prefix):853- return py_prefix, package_path854-855- site_parent, site_folder = os.path.split(package_path)856-857- # installed to a virtualenv858- if site_folder.lower() == "site-packages":859- parent, folder = os.path.split(site_parent)860-861- # Windows (prefix/lib/site-packages)862- if folder.lower() == "lib":863- return parent, package_path864-865- # Unix (prefix/lib/pythonX.Y/site-packages)866- if os.path.basename(parent).lower() == "lib":867- return os.path.dirname(parent), package_path868-869- # something else (prefix/site-packages)870- return site_parent, package_path871-872- # not installed873- return None, package_pathmodified:src/flask/templating.py+4 added-3 removed
15 unmodified lines16 from .signals import template_rendered17 18 if t.TYPE_CHECKING: # pragma: no cover19 from .app import Flask20+ from .sansio.app import App20- from .scaffold import Scaffold21+ from .sansio.scaffold import Scaffold22 23 24 def _default_template_ctx_processor() -> dict[str, t.Any]:25 """Default template context processor. Injects `request`,15 unmodified lines41 knowledge of how Flask's blueprint works so that it can prepend the42 name of the blueprint to referenced templates if necessary.43 """44 44- def __init__(self, app: Flask, **options: t.Any) -> None:45+ def __init__(self, app: App, **options: t.Any) -> None:46 if "loader" not in options:47 options["loader"] = app.create_global_jinja_loader()48 BaseEnvironment.__init__(self, **options)49 self.app = app3 unmodified lines53 """A loader that looks for templates in the application and all54 the blueprint folders.55 """56 56- def __init__(self, app: Flask) -> None:57+ def __init__(self, app: App) -> None:58 self.app = app59 60 def get_source( # type: ignore61 self, environment: Environment, template: str160 unmodified linesmodified:src/flask/typing.py+9 added-3 removed
3 unmodified lines4 5 if t.TYPE_CHECKING: # pragma: no cover6 from _typeshed.wsgi import WSGIApplication # noqa: F4017 from werkzeug.datastructures import Headers # noqa: F4018- from werkzeug.wrappers import Response # noqa: F4018+ from werkzeug.sansio.response import Response # noqa: F4019 10 # The possible types that are directly convertible or are a Response object.11 ResponseValue = t.Union[12 "Response",47 unmodified lines60 TeardownCallable = t.Union[61 t.Callable[[t.Optional[BaseException]], None],62 t.Callable[[t.Optional[BaseException]], t.Awaitable[None]],63 ]64-TemplateContextProcessorCallable = t.Callable[[], t.Dict[str, t.Any]]64+TemplateContextProcessorCallable = t.Union[65+ t.Callable[[], t.Dict[str, t.Any]],66+ t.Callable[[], t.Awaitable[t.Dict[str, t.Any]]],67+]68 TemplateFilterCallable = t.Callable[..., t.Any]69 TemplateGlobalCallable = t.Callable[..., t.Any]70 TemplateTestCallable = t.Callable[..., bool]71 URLDefaultCallable = t.Callable[[str, dict], None]4 unmodified lines76 # exceptions (and using a union type on the argument).77 # https://github.com/pallets/flask/issues/409578 # https://github.com/pallets/flask/issues/429579 # https://github.com/pallets/flask/issues/429777-ErrorHandlerCallable = t.Callable[[t.Any], ResponseReturnValue]80+ErrorHandlerCallable = t.Union[81+ t.Callable[[t.Any], ResponseReturnValue],82+ t.Callable[[t.Any], t.Awaitable[ResponseReturnValue]],83+]84 85 RouteCallable = t.Union[86 t.Callable[..., ResponseReturnValue],87 t.Callable[..., t.Awaitable[ResponseReturnValue]],1 unmodified linemodified:CHANGES.rst+2 added
2 unmodified lines3 4 Unreleased5 6 - Remove previously deprecated code. :pr:`5223`7+- Restructure the code such that the Flask (app) and Blueprint8+ classes have Sans-IO bases. :pr:`5127`9 10 11 Version 2.3.312 -------------1514 unmodified lines