Move file to sansio
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This is preperation for refactoring the files so that there are sansio and flask specific versions. This structure follows the Werkzeug structure/pattern.
authored by pgjones · committed by pgjones · parent 0e0e8dd · Browse files · 6 files·+3693 added−3693 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+3693 added−3693 removed
- other:+3693 added−3693 removed
Provenance
- Commit
a64588f- Tree
d558fc2- Author
pgjones <philip.graham.jones@googlemail.com>- Committer
pgjones <philip.graham.jones@googlemail.com>- Parent
0e0e8dd
6 files changed+3693 added−3693 removed
added:src/flask/sansio/app.py+2194 added
1+from __future__ import annotations2+3+import logging4+import os5+import sys6+import typing as t7+import weakref8+from collections.abc import Iterator as _abc_Iterator9+from datetime import timedelta10+from inspect import iscoroutinefunction11+from itertools import chain12+from types import TracebackType13+from urllib.parse import quote as _url_quote14+15+import click16+from werkzeug.datastructures import Headers17+from werkzeug.datastructures import ImmutableDict18+from werkzeug.exceptions import Aborter19+from werkzeug.exceptions import BadRequest20+from werkzeug.exceptions import BadRequestKeyError21+from werkzeug.exceptions import HTTPException22+from werkzeug.exceptions import InternalServerError23+from werkzeug.routing import BuildError24+from werkzeug.routing import Map25+from werkzeug.routing import MapAdapter26+from werkzeug.routing import RequestRedirect27+from werkzeug.routing import RoutingException28+from werkzeug.routing import Rule29+from werkzeug.serving import is_running_from_reloader30+from werkzeug.utils import cached_property31+from werkzeug.utils import redirect as _wz_redirect32+from werkzeug.wrappers import Response as BaseResponse33+34+from . import cli35+from . import typing as ft36+from .config import Config37+from .config import ConfigAttribute38+from .ctx import _AppCtxGlobals39+from .ctx import AppContext40+from .ctx import RequestContext41+from .globals import _cv_app42+from .globals import _cv_request43+from .globals import g44+from .globals import request45+from .globals import request_ctx46+from .globals import session47+from .helpers import _split_blueprint_path48+from .helpers import get_debug_flag49+from .helpers import get_flashed_messages50+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 setupmethod59+from .sessions import SecureCookieSessionInterface60+from .sessions import SessionInterface61+from .signals import appcontext_tearing_down62+from .signals import got_request_exception63+from .signals import request_finished64+from .signals import request_started65+from .signals import request_tearing_down66+from .templating import DispatchingJinjaLoader67+from .templating import Environment68+from .wrappers import Request69+from .wrappers import Response70+71+if t.TYPE_CHECKING: # pragma: no cover72+ from .blueprints import Blueprint73+ from .testing import FlaskClient74+ from .testing import FlaskCliRunner75+76+T_shell_context_processor = t.TypeVar(77+ "T_shell_context_processor", bound=ft.ShellContextProcessorCallable78+)79+T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)80+T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable)81+T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable)82+T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable)83+84+85+def _make_timedelta(value: timedelta | int | None) -> timedelta | None:86+ if value is None or isinstance(value, timedelta):87+ return value88+89+ return timedelta(seconds=value)90+91+92+class Flask(Scaffold):93+ """The flask object implements a WSGI application and acts as the central94+ object. It is passed the name of the module or package of the95+ application. Once it is created it will act as a central registry for96+ the view functions, the URL rules, template configuration and much more.97+98+ The name of the package is used to resolve resources from inside the99+ package or the folder the module is contained in depending on if the100+ package parameter resolves to an actual python package (a folder with101+ an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).102+103+ For more information about resource loading, see :func:`open_resource`.104+105+ Usually you create a :class:`Flask` instance in your main module or106+ in the :file:`__init__.py` file of your package like this::107+108+ from flask import Flask109+ app = Flask(__name__)110+111+ .. admonition:: About the First Parameter112+113+ The idea of the first parameter is to give Flask an idea of what114+ belongs to your application. This name is used to find resources115+ on the filesystem, can be used by extensions to improve debugging116+ information and a lot more.117+118+ So it's important what you provide there. If you are using a single119+ module, `__name__` is always the correct value. If you however are120+ using a package, it's usually recommended to hardcode the name of121+ your package there.122+123+ For example if your application is defined in :file:`yourapplication/app.py`124+ you should create it with one of the two versions below::125+126+ app = Flask('yourapplication')127+ app = Flask(__name__.split('.')[0])128+129+ Why is that? The application will work even with `__name__`, thanks130+ to how resources are looked up. However it will make debugging more131+ painful. Certain extensions can make assumptions based on the132+ import name of your application. For example the Flask-SQLAlchemy133+ extension will look for the code in your application that triggered134+ an SQL query in debug mode. If the import name is not properly set135+ up, that debugging information is lost. (For example it would only136+ pick up SQL queries in `yourapplication.app` and not137+ `yourapplication.views.frontend`)138+139+ .. versionadded:: 0.7140+ The `static_url_path`, `static_folder`, and `template_folder`141+ parameters were added.142+143+ .. versionadded:: 0.8144+ The `instance_path` and `instance_relative_config` parameters were145+ added.146+147+ .. versionadded:: 0.11148+ The `root_path` parameter was added.149+150+ .. versionadded:: 1.0151+ The ``host_matching`` and ``static_host`` parameters were added.152+153+ .. versionadded:: 1.0154+ The ``subdomain_matching`` parameter was added. Subdomain155+ matching needs to be enabled manually now. Setting156+ :data:`SERVER_NAME` does not implicitly enable it.157+158+ :param import_name: the name of the application package159+ :param static_url_path: can be used to specify a different path for the160+ static files on the web. Defaults to the name161+ of the `static_folder` folder.162+ :param static_folder: The folder with static files that is served at163+ ``static_url_path``. Relative to the application ``root_path``164+ or an absolute path. Defaults to ``'static'``.165+ :param static_host: the host to use when adding the static route.166+ Defaults to None. Required when using ``host_matching=True``167+ with a ``static_folder`` configured.168+ :param host_matching: set ``url_map.host_matching`` attribute.169+ Defaults to False.170+ :param subdomain_matching: consider the subdomain relative to171+ :data:`SERVER_NAME` when matching routes. Defaults to False.172+ :param template_folder: the folder that contains the templates that should173+ be used by the application. Defaults to174+ ``'templates'`` folder in the root path of the175+ application.176+ :param instance_path: An alternative instance path for the application.177+ By default the folder ``'instance'`` next to the178+ package or module is assumed to be the instance179+ path.180+ :param instance_relative_config: if set to ``True`` relative filenames181+ for loading the config are assumed to182+ be relative to the instance path instead183+ of the application root.184+ :param root_path: The path to the root of the application files.185+ This should only be set manually when it can't be detected186+ automatically, such as for namespace packages.187+ """188+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.294+ default_config = ImmutableDict(295+ {296+ "DEBUG": None,297+ "TESTING": False,298+ "PROPAGATE_EXCEPTIONS": None,299+ "SECRET_KEY": None,300+ "PERMANENT_SESSION_LIFETIME": timedelta(days=31),301+ "USE_X_SENDFILE": False,302+ "SERVER_NAME": None,303+ "APPLICATION_ROOT": "/",304+ "SESSION_COOKIE_NAME": "session",305+ "SESSION_COOKIE_DOMAIN": None,306+ "SESSION_COOKIE_PATH": None,307+ "SESSION_COOKIE_HTTPONLY": True,308+ "SESSION_COOKIE_SECURE": False,309+ "SESSION_COOKIE_SAMESITE": None,310+ "SESSION_REFRESH_EACH_REQUEST": True,311+ "MAX_CONTENT_LENGTH": None,312+ "SEND_FILE_MAX_AGE_DEFAULT": None,313+ "TRAP_BAD_REQUEST_ERRORS": None,314+ "TRAP_HTTP_EXCEPTIONS": False,315+ "EXPLAIN_TEMPLATE_LOADING": False,316+ "PREFERRED_URL_SCHEME": "http",317+ "TEMPLATES_AUTO_RELOAD": None,318+ "MAX_COOKIE_SIZE": 4093,319+ }320+ )321+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 = Rule327+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 = Map333+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+348+ #: the session interface to use. By default an instance of349+ #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.350+ #:351+ #: .. versionadded:: 0.8352+ session_interface: SessionInterface = SecureCookieSessionInterface()353+354+ def __init__(355+ self,356+ import_name: str,357+ static_url_path: str | None = None,358+ static_folder: str | os.PathLike | None = "static",359+ static_host: str | None = None,360+ host_matching: bool = False,361+ subdomain_matching: bool = False,362+ template_folder: str | os.PathLike | None = "templates",363+ instance_path: str | None = None,364+ instance_relative_config: bool = False,365+ root_path: str | None = None,366+ ):367+ super().__init__(368+ import_name=import_name,369+ static_folder=static_folder,370+ static_url_path=static_url_path,371+ template_folder=template_folder,372+ root_path=root_path,373+ )374+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+486+ # Add a static route using the provided static_url_path, static_host,487+ # and static_folder if there is a configured static_folder.488+ # Note we do this without checking if static_folder exists.489+ # For one, it might be created while the server is running (e.g. during490+ # development). Also, Google App Engine stores static files somewhere491+ if self.has_static_folder:492+ assert (493+ bool(static_host) == host_matching494+ ), "Invalid static_host/host_matching combination"495+ # Use a weakref to avoid creating a reference cycle between the app496+ # and the view function (see #3761).497+ self_ref = weakref.ref(self)498+ self.add_url_rule(499+ f"{self.static_url_path}/<path:filename>",500+ endpoint="static",501+ host=static_host,502+ view_func=lambda **kw: self_ref().send_static_file(**kw), # type: ignore # noqa: B950503+ )504+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.name508+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+ )520+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.528+529+ .. versionadded:: 0.8530+ """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_name537+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`.542+543+ In debug mode, the logger's :attr:`~logging.Logger.level` will544+ be set to :data:`~logging.DEBUG`.545+546+ If there are no handlers configured, a default handler will be547+ added. See :doc:`/logging` for more information.548+549+ .. versionchanged:: 1.1.0550+ The logger takes the same name as :attr:`name` rather than551+ hard-coding ``"flask.app"``.552+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.560+561+ .. versionadded:: 0.3562+ """563+ return create_logger(self)564+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.572+ """573+ return self.create_jinja_environment()574+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.581+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)590+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.595+596+ By default, this creates an instance of :attr:`aborter_class`,597+ which defaults to :class:`werkzeug.exceptions.Aborter`.598+599+ .. versionadded:: 2.2600+ """601+ return self.aborter_class()602+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.608+609+ .. versionadded:: 0.8610+ """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")615+616+ def open_instance_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:617+ """Opens a resource from the application's instance folder618+ (:attr:`instance_path`). Otherwise works like619+ :meth:`open_resource`. Instance resources can also be opened for620+ writing.621+622+ :param resource: the name of the resource. To access resources within623+ subfolders use forward slashes as separator.624+ :param mode: resource file opening mode, default is 'rb'.625+ """626+ return open(os.path.join(self.instance_path, resource), mode)627+628+ def create_jinja_environment(self) -> Environment:629+ """Create the Jinja environment based on :attr:`jinja_options`630+ and the various Jinja-related methods of the app. Changing631+ :attr:`jinja_options` after this will have no effect. Also adds632+ Flask-related globals and filters to the environment.633+634+ .. versionchanged:: 0.11635+ ``Environment.auto_reload`` set in accordance with636+ ``TEMPLATES_AUTO_RELOAD`` configuration option.637+638+ .. versionadded:: 0.5639+ """640+ options = dict(self.jinja_options)641+642+ if "autoescape" not in options:643+ options["autoescape"] = self.select_jinja_autoescape644+645+ if "auto_reload" not in options:646+ auto_reload = self.config["TEMPLATES_AUTO_RELOAD"]647+648+ if auto_reload is None:649+ auto_reload = self.debug650+651+ options["auto_reload"] = auto_reload652+653+ rv = self.jinja_environment(self, **options)654+ rv.globals.update(655+ url_for=self.url_for,656+ get_flashed_messages=get_flashed_messages,657+ config=self.config,658+ # request, session and g are normally added with the659+ # context processor for efficiency reasons but for imported660+ # templates we also want the proxies in there.661+ request=request,662+ session=session,663+ g=g,664+ )665+ rv.policies["json.dumps_function"] = self.json.dumps666+ return rv667+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.673+674+ The global loader dispatches between the loaders of the application675+ and the individual blueprints.676+677+ .. versionadded:: 0.7678+ """679+ return DispatchingJinjaLoader(self)680+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`.684+685+ .. versionchanged:: 2.2686+ Autoescaping is now enabled by default for ``.svg`` files.687+688+ .. versionadded:: 0.5689+ """690+ if filename is None:691+ return True692+ return filename.endswith((".html", ".htm", ".xml", ".xhtml", ".svg"))693+694+ def update_template_context(self, context: dict) -> None:695+ """Update the template context with some commonly used variables.696+ This injects request, session, config and g into the template697+ context as well as everything template context processors want698+ to inject. Note that the as of Flask 0.6, the original values699+ in the context will not be overridden if a context processor700+ decides to return a value with the same key.701+702+ :param context: the context as a dictionary that is updated in place703+ to add extra variables.704+ """705+ names: t.Iterable[str | None] = (None,)706+707+ # A template may be rendered outside a request context.708+ if request:709+ names = chain(names, reversed(request.blueprints))710+711+ # The values passed to render_template take precedence. Keep a712+ # copy to re-apply after all context functions.713+ orig_ctx = context.copy()714+715+ for name in names:716+ if name in self.template_context_processors:717+ for func in self.template_context_processors[name]:718+ context.update(func())719+720+ context.update(orig_ctx)721+722+ def make_shell_context(self) -> dict:723+ """Returns the shell context for an interactive shell for this724+ application. This runs all the registered shell context725+ processors.726+727+ .. versionadded:: 0.11728+ """729+ rv = {"app": self, "g": g}730+ for processor in self.shell_context_processors:731+ rv.update(processor())732+ return rv733+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+754+ def run(755+ self,756+ host: str | None = None,757+ port: int | None = None,758+ debug: bool | None = None,759+ load_dotenv: bool = True,760+ **options: t.Any,761+ ) -> None:762+ """Runs the application on a local development server.763+764+ Do not use ``run()`` in a production setting. It is not intended to765+ meet security and performance requirements for a production server.766+ Instead, see :doc:`/deploying/index` for WSGI server recommendations.767+768+ If the :attr:`debug` flag is set the server will automatically reload769+ for code changes and show a debugger in case an exception happened.770+771+ If you want to run the application in debug mode, but disable the772+ code execution on the interactive debugger, you can pass773+ ``use_evalex=False`` as parameter. This will keep the debugger's774+ traceback screen active, but disable code execution.775+776+ It is not recommended to use this function for development with777+ automatic reloading as this is badly supported. Instead you should778+ be using the :command:`flask` command line script's ``run`` support.779+780+ .. admonition:: Keep in Mind781+782+ Flask will suppress any server error with a generic error page783+ unless it is in debug mode. As such to enable just the784+ interactive debugger without the code reloading, you have to785+ invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.786+ Setting ``use_debugger`` to ``True`` without being in debug mode787+ won't catch any exceptions because there won't be any to788+ catch.789+790+ :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to791+ have the server available externally as well. Defaults to792+ ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable793+ if present.794+ :param port: the port of the webserver. Defaults to ``5000`` or the795+ port defined in the ``SERVER_NAME`` config variable if present.796+ :param debug: if given, enable or disable debug mode. See797+ :attr:`debug`.798+ :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`799+ files to set environment variables. Will also change the working800+ directory to the directory containing the first file found.801+ :param options: the options to be forwarded to the underlying Werkzeug802+ server. See :func:`werkzeug.serving.run_simple` for more803+ information.804+805+ .. versionchanged:: 1.0806+ If installed, python-dotenv will be used to load environment807+ variables from :file:`.env` and :file:`.flaskenv` files.808+809+ The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.810+811+ Threaded mode is enabled by default.812+813+ .. versionchanged:: 0.10814+ The default port is now picked from the ``SERVER_NAME``815+ variable.816+ """817+ # Ignore this call so that it doesn't start another server if818+ # the 'flask run' command is used.819+ if os.environ.get("FLASK_RUN_FROM_CLI") == "true":820+ if not is_running_from_reloader():821+ click.secho(822+ " * Ignoring a call to 'app.run()' that would block"823+ " the current 'flask' CLI command.\n"824+ " Only call 'app.run()' in an 'if __name__ =="825+ ' "__main__"\' guard.',826+ fg="red",827+ )828+829+ return830+831+ if get_load_dotenv(load_dotenv):832+ cli.load_dotenv()833+834+ # if set, env var overrides existing value835+ if "FLASK_DEBUG" in os.environ:836+ self.debug = get_debug_flag()837+838+ # debug passed to method overrides all other sources839+ if debug is not None:840+ self.debug = bool(debug)841+842+ server_name = self.config.get("SERVER_NAME")843+ sn_host = sn_port = None844+845+ if server_name:846+ sn_host, _, sn_port = server_name.partition(":")847+848+ if not host:849+ if sn_host:850+ host = sn_host851+ else:852+ host = "127.0.0.1"853+854+ if port or port == 0:855+ port = int(port)856+ elif sn_port:857+ port = int(sn_port)858+ else:859+ port = 5000860+861+ options.setdefault("use_reloader", self.debug)862+ options.setdefault("use_debugger", self.debug)863+ options.setdefault("threaded", True)864+865+ cli.show_server_banner(self.debug, self.name)866+867+ from werkzeug.serving import run_simple868+869+ try:870+ run_simple(t.cast(str, host), port, self, **options)871+ finally:872+ # reset the first request information if the development server873+ # reset normally. This makes it possible to restart the server874+ # without reloader and that stuff from an interactive shell.875+ self._got_first_request = False876+877+ def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> FlaskClient:878+ """Creates a test client for this application. For information879+ about unit testing head over to :doc:`/testing`.880+881+ Note that if you are testing for assertions or exceptions in your882+ application code, you must set ``app.testing = True`` in order for the883+ exceptions to propagate to the test client. Otherwise, the exception884+ will be handled by the application (not visible to the test client) and885+ the only indication of an AssertionError or other exception will be a886+ 500 status code response to the test client. See the :attr:`testing`887+ attribute. For example::888+889+ app.testing = True890+ client = app.test_client()891+892+ The test client can be used in a ``with`` block to defer the closing down893+ of the context until the end of the ``with`` block. This is useful if894+ you want to access the context locals for testing::895+896+ with app.test_client() as c:897+ rv = c.get('/?vodka=42')898+ assert request.args['vodka'] == '42'899+900+ Additionally, you may pass optional keyword arguments that will then901+ be passed to the application's :attr:`test_client_class` constructor.902+ For example::903+904+ from flask.testing import FlaskClient905+906+ class CustomClient(FlaskClient):907+ def __init__(self, *args, **kwargs):908+ self._authentication = kwargs.pop("authentication")909+ super(CustomClient,self).__init__( *args, **kwargs)910+911+ app.test_client_class = CustomClient912+ client = app.test_client(authentication='Basic ....')913+914+ See :class:`~flask.testing.FlaskClient` for more information.915+916+ .. versionchanged:: 0.4917+ added support for ``with`` block usage for the client.918+919+ .. versionadded:: 0.7920+ The `use_cookies` parameter was added as well as the ability921+ to override the client to be used by setting the922+ :attr:`test_client_class` attribute.923+924+ .. versionchanged:: 0.11925+ Added `**kwargs` to support passing additional keyword arguments to926+ the constructor of :attr:`test_client_class`.927+ """928+ cls = self.test_client_class929+ if cls is None:930+ from .testing import FlaskClient as cls931+ return cls( # type: ignore932+ self, self.response_class, use_cookies=use_cookies, **kwargs933+ )934+935+ def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner:936+ """Create a CLI runner for testing CLI commands.937+ See :ref:`testing-cli`.938+939+ Returns an instance of :attr:`test_cli_runner_class`, by default940+ :class:`~flask.testing.FlaskCliRunner`. The Flask app object is941+ passed as the first argument.942+943+ .. versionadded:: 1.0944+ """945+ cls = self.test_cli_runner_class946+947+ if cls is None:948+ from .testing import FlaskCliRunner as cls949+950+ return cls(self, **kwargs) # type: ignore951+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+1229+ def handle_http_exception(1230+ self, e: HTTPException1231+ ) -> HTTPException | ft.ResponseReturnValue:1232+ """Handles an HTTP exception. By default this will invoke the1233+ registered error handlers and fall back to returning the1234+ exception as response.1235+1236+ .. versionchanged:: 1.0.31237+ ``RoutingException``, used internally for actions such as1238+ slash redirects during routing, is not passed to error1239+ handlers.1240+1241+ .. versionchanged:: 1.01242+ Exceptions are looked up by code *and* by MRO, so1243+ ``HTTPException`` subclasses can be handled with a catch-all1244+ handler for the base ``HTTPException``.1245+1246+ .. versionadded:: 0.31247+ """1248+ # Proxy exceptions don't have error codes. We want to always return1249+ # those unchanged as errors1250+ if e.code is None:1251+ return e1252+1253+ # RoutingExceptions are used internally to trigger routing1254+ # actions, such as slash redirects raising RequestRedirect. They1255+ # are not raised or handled in user code.1256+ if isinstance(e, RoutingException):1257+ return e1258+1259+ handler = self._find_error_handler(e)1260+ if handler is None:1261+ return e1262+ return self.ensure_sync(handler)(e)1263+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+1299+ def handle_user_exception(1300+ self, e: Exception1301+ ) -> HTTPException | ft.ResponseReturnValue:1302+ """This method is called whenever an exception occurs that1303+ should be handled. A special case is :class:`~werkzeug1304+ .exceptions.HTTPException` which is forwarded to the1305+ :meth:`handle_http_exception` method. This function will either1306+ return a response value or reraise the exception with the same1307+ traceback.1308+1309+ .. versionchanged:: 1.01310+ Key errors raised from request data like ``form`` show the1311+ bad key in debug mode rather than a generic bad request1312+ message.1313+1314+ .. versionadded:: 0.71315+ """1316+ if isinstance(e, BadRequestKeyError) and (1317+ self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]1318+ ):1319+ e.show_exception = True1320+1321+ if isinstance(e, HTTPException) and not self.trap_http_exception(e):1322+ return self.handle_http_exception(e)1323+1324+ handler = self._find_error_handler(e)1325+1326+ if handler is None:1327+ raise1328+1329+ return self.ensure_sync(handler)(e)1330+1331+ def handle_exception(self, e: Exception) -> Response:1332+ """Handle an exception that did not have an error handler1333+ associated with it, or that was raised from an error handler.1334+ This always causes a 500 ``InternalServerError``.1335+1336+ Always sends the :data:`got_request_exception` signal.1337+1338+ If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug1339+ mode, the error will be re-raised so that the debugger can1340+ display it. Otherwise, the original exception is logged, and1341+ an :exc:`~werkzeug.exceptions.InternalServerError` is returned.1342+1343+ If an error handler is registered for ``InternalServerError`` or1344+ ``500``, it will be used. For consistency, the handler will1345+ always receive the ``InternalServerError``. The original1346+ unhandled exception is available as ``e.original_exception``.1347+1348+ .. versionchanged:: 1.1.01349+ Always passes the ``InternalServerError`` instance to the1350+ handler, setting ``original_exception`` to the unhandled1351+ error.1352+1353+ .. versionchanged:: 1.1.01354+ ``after_request`` functions and other finalization is done1355+ even for the default 500 response when there is no handler.1356+1357+ .. versionadded:: 0.31358+ """1359+ exc_info = sys.exc_info()1360+ got_request_exception.send(self, _async_wrapper=self.ensure_sync, exception=e)1361+ propagate = self.config["PROPAGATE_EXCEPTIONS"]1362+1363+ if propagate is None:1364+ propagate = self.testing or self.debug1365+1366+ if propagate:1367+ # Re-raise if called with an active exception, otherwise1368+ # raise the passed in exception.1369+ if exc_info[1] is e:1370+ raise1371+1372+ raise e1373+1374+ self.log_exception(exc_info)1375+ server_error: InternalServerError | ft.ResponseReturnValue1376+ server_error = InternalServerError(original_exception=e)1377+ handler = self._find_error_handler(server_error)1378+1379+ if handler is not None:1380+ server_error = self.ensure_sync(handler)(server_error)1381+1382+ return self.finalize_request(server_error, from_error_handler=True)1383+1384+ def log_exception(1385+ self,1386+ exc_info: (tuple[type, BaseException, TracebackType] | tuple[None, None, None]),1387+ ) -> None:1388+ """Logs an exception. This is called by :meth:`handle_exception`1389+ if debugging is disabled and right before the handler is called.1390+ The default implementation logs the exception as error on the1391+ :attr:`logger`.1392+1393+ .. versionadded:: 0.81394+ """1395+ self.logger.error(1396+ f"Exception on {request.path} [{request.method}]", exc_info=exc_info1397+ )1398+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+1427+ def dispatch_request(self) -> ft.ResponseReturnValue:1428+ """Does the request dispatching. Matches the URL and returns the1429+ return value of the view or error handler. This does not have to1430+ be a response object. In order to convert the return value to a1431+ proper response object, call :func:`make_response`.1432+1433+ .. versionchanged:: 0.71434+ This no longer does the exception handling, this code was1435+ moved to the new :meth:`full_dispatch_request`.1436+ """1437+ req = request_ctx.request1438+ if req.routing_exception is not None:1439+ self.raise_routing_exception(req)1440+ rule: Rule = req.url_rule # type: ignore[assignment]1441+ # if we provide automatic options for this URL and the1442+ # request came with the OPTIONS method, reply automatically1443+ if (1444+ getattr(rule, "provide_automatic_options", False)1445+ and req.method == "OPTIONS"1446+ ):1447+ return self.make_default_options_response()1448+ # otherwise dispatch to the handler for that endpoint1449+ view_args: dict[str, t.Any] = req.view_args # type: ignore[assignment]1450+ return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)1451+1452+ def full_dispatch_request(self) -> Response:1453+ """Dispatches the request and on top of that performs request1454+ pre and postprocessing as well as HTTP exception catching and1455+ error handling.1456+1457+ .. versionadded:: 0.71458+ """1459+ self._got_first_request = True1460+1461+ try:1462+ request_started.send(self, _async_wrapper=self.ensure_sync)1463+ rv = self.preprocess_request()1464+ if rv is None:1465+ rv = self.dispatch_request()1466+ except Exception as e:1467+ rv = self.handle_user_exception(e)1468+ return self.finalize_request(rv)1469+1470+ def finalize_request(1471+ self,1472+ rv: ft.ResponseReturnValue | HTTPException,1473+ from_error_handler: bool = False,1474+ ) -> Response:1475+ """Given the return value from a view function this finalizes1476+ the request by converting it into a response and invoking the1477+ postprocessing functions. This is invoked for both normal1478+ request dispatching as well as error handlers.1479+1480+ Because this means that it might be called as a result of a1481+ failure a special safe mode is available which can be enabled1482+ with the `from_error_handler` flag. If enabled, failures in1483+ response processing will be logged and otherwise ignored.1484+1485+ :internal:1486+ """1487+ response = self.make_response(rv)1488+ try:1489+ response = self.process_response(response)1490+ request_finished.send(1491+ self, _async_wrapper=self.ensure_sync, response=response1492+ )1493+ except Exception:1494+ if not from_error_handler:1495+ raise1496+ self.logger.exception(1497+ "Request finalizing failed with an error while handling an error"1498+ )1499+ return response1500+1501+ def make_default_options_response(self) -> Response:1502+ """This method is called to create the default ``OPTIONS`` response.1503+ This can be changed through subclassing to change the default1504+ behavior of ``OPTIONS`` responses.1505+1506+ .. versionadded:: 0.71507+ """1508+ adapter = request_ctx.url_adapter1509+ methods = adapter.allowed_methods() # type: ignore[union-attr]1510+ rv = self.response_class()1511+ rv.allow.update(methods)1512+ return rv1513+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+1524+ def ensure_sync(self, func: t.Callable) -> t.Callable:1525+ """Ensure that the function is synchronous for WSGI workers.1526+ Plain ``def`` functions are returned as-is. ``async def``1527+ functions are wrapped to run and wait for the response.1528+1529+ Override this method to change how the app runs async views.1530+1531+ .. versionadded:: 2.01532+ """1533+ if iscoroutinefunction(func):1534+ return self.async_to_sync(func)1535+1536+ return func1537+1538+ def async_to_sync(1539+ self, func: t.Callable[..., t.Coroutine]1540+ ) -> t.Callable[..., t.Any]:1541+ """Return a sync function that will run the coroutine function.1542+1543+ .. code-block:: python1544+1545+ result = app.async_to_sync(func)(*args, **kwargs)1546+1547+ Override this method to change how the app converts async code1548+ to be synchronously callable.1549+1550+ .. versionadded:: 2.01551+ """1552+ try:1553+ from asgiref.sync import async_to_sync as asgiref_async_to_sync1554+ except ImportError:1555+ raise RuntimeError(1556+ "Install Flask with the 'async' extra in order to use async views."1557+ ) from None1558+1559+ return asgiref_async_to_sync(func)1560+1561+ def url_for(1562+ self,1563+ endpoint: str,1564+ *,1565+ _anchor: str | None = None,1566+ _method: str | None = None,1567+ _scheme: str | None = None,1568+ _external: bool | None = None,1569+ **values: t.Any,1570+ ) -> str:1571+ """Generate a URL to the given endpoint with the given values.1572+1573+ This is called by :func:`flask.url_for`, and can be called1574+ directly as well.1575+1576+ An *endpoint* is the name of a URL rule, usually added with1577+ :meth:`@app.route() <route>`, and usually the same name as the1578+ view function. A route defined in a :class:`~flask.Blueprint`1579+ will prepend the blueprint's name separated by a ``.`` to the1580+ endpoint.1581+1582+ In some cases, such as email messages, you want URLs to include1583+ the scheme and domain, like ``https://example.com/hello``. When1584+ not in an active request, URLs will be external by default, but1585+ this requires setting :data:`SERVER_NAME` so Flask knows what1586+ domain to use. :data:`APPLICATION_ROOT` and1587+ :data:`PREFERRED_URL_SCHEME` should also be configured as1588+ needed. This config is only used when not in an active request.1589+1590+ Functions can be decorated with :meth:`url_defaults` to modify1591+ keyword arguments before the URL is built.1592+1593+ If building fails for some reason, such as an unknown endpoint1594+ or incorrect values, the app's :meth:`handle_url_build_error`1595+ method is called. If that returns a string, that is returned,1596+ otherwise a :exc:`~werkzeug.routing.BuildError` is raised.1597+1598+ :param endpoint: The endpoint name associated with the URL to1599+ generate. If this starts with a ``.``, the current blueprint1600+ name (if any) will be used.1601+ :param _anchor: If given, append this as ``#anchor`` to the URL.1602+ :param _method: If given, generate the URL associated with this1603+ method for the endpoint.1604+ :param _scheme: If given, the URL will have this scheme if it1605+ is external.1606+ :param _external: If given, prefer the URL to be internal1607+ (False) or require it to be external (True). External URLs1608+ include the scheme and domain. When not in an active1609+ request, URLs are external by default.1610+ :param values: Values to use for the variable parts of the URL1611+ rule. Unknown keys are appended as query string arguments,1612+ like ``?a=b&c=d``.1613+1614+ .. versionadded:: 2.21615+ Moved from ``flask.url_for``, which calls this method.1616+ """1617+ req_ctx = _cv_request.get(None)1618+1619+ if req_ctx is not None:1620+ url_adapter = req_ctx.url_adapter1621+ blueprint_name = req_ctx.request.blueprint1622+1623+ # If the endpoint starts with "." and the request matches a1624+ # blueprint, the endpoint is relative to the blueprint.1625+ if endpoint[:1] == ".":1626+ if blueprint_name is not None:1627+ endpoint = f"{blueprint_name}{endpoint}"1628+ else:1629+ endpoint = endpoint[1:]1630+1631+ # When in a request, generate a URL without scheme and1632+ # domain by default, unless a scheme is given.1633+ if _external is None:1634+ _external = _scheme is not None1635+ else:1636+ app_ctx = _cv_app.get(None)1637+1638+ # If called by helpers.url_for, an app context is active,1639+ # use its url_adapter. Otherwise, app.url_for was called1640+ # directly, build an adapter.1641+ if app_ctx is not None:1642+ url_adapter = app_ctx.url_adapter1643+ else:1644+ url_adapter = self.create_url_adapter(None)1645+1646+ if url_adapter is None:1647+ raise RuntimeError(1648+ "Unable to build URLs outside an active request"1649+ " without 'SERVER_NAME' configured. Also configure"1650+ " 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as"1651+ " needed."1652+ )1653+1654+ # When outside a request, generate a URL with scheme and1655+ # domain by default.1656+ if _external is None:1657+ _external = True1658+1659+ # It is an error to set _scheme when _external=False, in order1660+ # to avoid accidental insecure URLs.1661+ if _scheme is not None and not _external:1662+ raise ValueError("When specifying '_scheme', '_external' must be True.")1663+1664+ self.inject_url_defaults(endpoint, values)1665+1666+ try:1667+ rv = url_adapter.build( # type: ignore[union-attr]1668+ endpoint,1669+ values,1670+ method=_method,1671+ url_scheme=_scheme,1672+ force_external=_external,1673+ )1674+ except BuildError as error:1675+ values.update(1676+ _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external1677+ )1678+ return self.handle_url_build_error(error, endpoint, values)1679+1680+ if _anchor is not None:1681+ _anchor = _url_quote(_anchor, safe="%!#$&'()*+,/:;=?@")1682+ rv = f"{rv}#{_anchor}"1683+1684+ return rv1685+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+1700+ def make_response(self, rv: ft.ResponseReturnValue) -> Response:1701+ """Convert the return value from a view function to an instance of1702+ :attr:`response_class`.1703+1704+ :param rv: the return value from the view function. The view function1705+ must return a response. Returning ``None``, or the view ending1706+ without returning, is not allowed. The following types are allowed1707+ for ``view_rv``:1708+1709+ ``str``1710+ A response object is created with the string encoded to UTF-81711+ as the body.1712+1713+ ``bytes``1714+ A response object is created with the bytes as the body.1715+1716+ ``dict``1717+ A dictionary that will be jsonify'd before being returned.1718+1719+ ``list``1720+ A list that will be jsonify'd before being returned.1721+1722+ ``generator`` or ``iterator``1723+ A generator that returns ``str`` or ``bytes`` to be1724+ streamed as the response.1725+1726+ ``tuple``1727+ Either ``(body, status, headers)``, ``(body, status)``, or1728+ ``(body, headers)``, where ``body`` is any of the other types1729+ allowed here, ``status`` is a string or an integer, and1730+ ``headers`` is a dictionary or a list of ``(key, value)``1731+ tuples. If ``body`` is a :attr:`response_class` instance,1732+ ``status`` overwrites the exiting value and ``headers`` are1733+ extended.1734+1735+ :attr:`response_class`1736+ The object is returned unchanged.1737+1738+ other :class:`~werkzeug.wrappers.Response` class1739+ The object is coerced to :attr:`response_class`.1740+1741+ :func:`callable`1742+ The function is called as a WSGI application. The result is1743+ used to create a response object.1744+1745+ .. versionchanged:: 2.21746+ A generator will be converted to a streaming response.1747+ A list will be converted to a JSON response.1748+1749+ .. versionchanged:: 1.11750+ A dict will be converted to a JSON response.1751+1752+ .. versionchanged:: 0.91753+ Previously a tuple was interpreted as the arguments for the1754+ response object.1755+ """1756+1757+ status = headers = None1758+1759+ # unpack tuple returns1760+ if isinstance(rv, tuple):1761+ len_rv = len(rv)1762+1763+ # a 3-tuple is unpacked directly1764+ if len_rv == 3:1765+ rv, status, headers = rv # type: ignore[misc]1766+ # decide if a 2-tuple has status or headers1767+ elif len_rv == 2:1768+ if isinstance(rv[1], (Headers, dict, tuple, list)):1769+ rv, headers = rv1770+ else:1771+ rv, status = rv # type: ignore[assignment,misc]1772+ # other sized tuples are not allowed1773+ else:1774+ raise TypeError(1775+ "The view function did not return a valid response tuple."1776+ " The tuple must have the form (body, status, headers),"1777+ " (body, status), or (body, headers)."1778+ )1779+1780+ # the body must not be None1781+ if rv is None:1782+ raise TypeError(1783+ f"The view function for {request.endpoint!r} did not"1784+ " return a valid response. The function either returned"1785+ " None or ended without a return statement."1786+ )1787+1788+ # make sure the body is an instance of the response class1789+ if not isinstance(rv, self.response_class):1790+ if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, _abc_Iterator):1791+ # let the response class set the status and headers instead of1792+ # waiting to do it manually, so that the class can handle any1793+ # special logic1794+ rv = self.response_class(1795+ rv,1796+ status=status,1797+ headers=headers, # type: ignore[arg-type]1798+ )1799+ status = headers = None1800+ elif isinstance(rv, (dict, list)):1801+ rv = self.json.response(rv)1802+ elif isinstance(rv, BaseResponse) or callable(rv):1803+ # evaluate a WSGI callable, or coerce a different response1804+ # class to the correct type1805+ try:1806+ rv = self.response_class.force_type(1807+ rv, request.environ # type: ignore[arg-type]1808+ )1809+ except TypeError as e:1810+ raise TypeError(1811+ f"{e}\nThe view function did not return a valid"1812+ " response. The return type must be a string,"1813+ " dict, list, tuple with headers or status,"1814+ " Response instance, or WSGI callable, but it"1815+ f" was a {type(rv).__name__}."1816+ ).with_traceback(sys.exc_info()[2]) from None1817+ else:1818+ raise TypeError(1819+ "The view function did not return a valid"1820+ " response. The return type must be a string,"1821+ " dict, list, tuple with headers or status,"1822+ " Response instance, or WSGI callable, but it was a"1823+ f" {type(rv).__name__}."1824+ )1825+1826+ rv = t.cast(Response, rv)1827+ # prefer the status if it was provided1828+ if status is not None:1829+ if isinstance(status, (str, bytes, bytearray)):1830+ rv.status = status1831+ else:1832+ rv.status_code = status1833+1834+ # extend existing headers with provided headers1835+ if headers:1836+ rv.headers.update(headers) # type: ignore[arg-type]1837+1838+ return rv1839+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+1935+ def preprocess_request(self) -> ft.ResponseReturnValue | None:1936+ """Called before the request is dispatched. Calls1937+ :attr:`url_value_preprocessors` registered with the app and the1938+ current blueprint (if any). Then calls :attr:`before_request_funcs`1939+ registered with the app and the blueprint.1940+1941+ If any :meth:`before_request` handler returns a non-None value, the1942+ value is handled as if it was the return value from the view, and1943+ further request handling is stopped.1944+ """1945+ names = (None, *reversed(request.blueprints))1946+1947+ for name in names:1948+ if name in self.url_value_preprocessors:1949+ for url_func in self.url_value_preprocessors[name]:1950+ url_func(request.endpoint, request.view_args)1951+1952+ for name in names:1953+ if name in self.before_request_funcs:1954+ for before_func in self.before_request_funcs[name]:1955+ rv = self.ensure_sync(before_func)()1956+1957+ if rv is not None:1958+ return rv1959+1960+ return None1961+1962+ def process_response(self, response: Response) -> Response:1963+ """Can be overridden in order to modify the response object1964+ before it's sent to the WSGI server. By default this will1965+ call all the :meth:`after_request` decorated functions.1966+1967+ .. versionchanged:: 0.51968+ As of Flask 0.5 the functions registered for after request1969+ execution are called in reverse order of registration.1970+1971+ :param response: a :attr:`response_class` object.1972+ :return: a new response object or the same, has to be an1973+ instance of :attr:`response_class`.1974+ """1975+ ctx = request_ctx._get_current_object() # type: ignore[attr-defined]1976+1977+ for func in ctx._after_request_functions:1978+ response = self.ensure_sync(func)(response)1979+1980+ for name in chain(request.blueprints, (None,)):1981+ if name in self.after_request_funcs:1982+ for func in reversed(self.after_request_funcs[name]):1983+ response = self.ensure_sync(func)(response)1984+1985+ if not self.session_interface.is_null_session(ctx.session):1986+ self.session_interface.save_session(self, ctx.session, response)1987+1988+ return response1989+1990+ def do_teardown_request(1991+ self, exc: BaseException | None = _sentinel # type: ignore1992+ ) -> None:1993+ """Called after the request is dispatched and the response is1994+ returned, right before the request context is popped.1995+1996+ This calls all functions decorated with1997+ :meth:`teardown_request`, and :meth:`Blueprint.teardown_request`1998+ if a blueprint handled the request. Finally, the1999+ :data:`request_tearing_down` signal is sent.2000+2001+ This is called by2002+ :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`,2003+ which may be delayed during testing to maintain access to2004+ resources.2005+2006+ :param exc: An unhandled exception raised while dispatching the2007+ request. Detected from the current exception information if2008+ not passed. Passed to each teardown function.2009+2010+ .. versionchanged:: 0.92011+ Added the ``exc`` argument.2012+ """2013+ if exc is _sentinel:2014+ exc = sys.exc_info()[1]2015+2016+ for name in chain(request.blueprints, (None,)):2017+ if name in self.teardown_request_funcs:2018+ for func in reversed(self.teardown_request_funcs[name]):2019+ self.ensure_sync(func)(exc)2020+2021+ request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)2022+2023+ def do_teardown_appcontext(2024+ self, exc: BaseException | None = _sentinel # type: ignore2025+ ) -> None:2026+ """Called right before the application context is popped.2027+2028+ When handling a request, the application context is popped2029+ after the request context. See :meth:`do_teardown_request`.2030+2031+ This calls all functions decorated with2032+ :meth:`teardown_appcontext`. Then the2033+ :data:`appcontext_tearing_down` signal is sent.2034+2035+ This is called by2036+ :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.2037+2038+ .. versionadded:: 0.92039+ """2040+ if exc is _sentinel:2041+ exc = sys.exc_info()[1]2042+2043+ for func in reversed(self.teardown_appcontext_funcs):2044+ self.ensure_sync(func)(exc)2045+2046+ appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)2047+2048+ def app_context(self) -> AppContext:2049+ """Create an :class:`~flask.ctx.AppContext`. Use as a ``with``2050+ block to push the context, which will make :data:`current_app`2051+ point at this application.2052+2053+ An application context is automatically pushed by2054+ :meth:`RequestContext.push() <flask.ctx.RequestContext.push>`2055+ when handling a request, and when running a CLI command. Use2056+ this to manually create a context outside of these situations.2057+2058+ ::2059+2060+ with app.app_context():2061+ init_db()2062+2063+ See :doc:`/appcontext`.2064+2065+ .. versionadded:: 0.92066+ """2067+ return AppContext(self)2068+2069+ def request_context(self, environ: dict) -> RequestContext:2070+ """Create a :class:`~flask.ctx.RequestContext` representing a2071+ WSGI environment. Use a ``with`` block to push the context,2072+ which will make :data:`request` point at this request.2073+2074+ See :doc:`/reqcontext`.2075+2076+ Typically you should not call this from your own code. A request2077+ context is automatically pushed by the :meth:`wsgi_app` when2078+ handling a request. Use :meth:`test_request_context` to create2079+ an environment and context instead of this method.2080+2081+ :param environ: a WSGI environment2082+ """2083+ return RequestContext(self, environ)2084+2085+ def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> RequestContext:2086+ """Create a :class:`~flask.ctx.RequestContext` for a WSGI2087+ environment created from the given values. This is mostly useful2088+ during testing, where you may want to run a function that uses2089+ request data without dispatching a full request.2090+2091+ See :doc:`/reqcontext`.2092+2093+ Use a ``with`` block to push the context, which will make2094+ :data:`request` point at the request for the created2095+ environment. ::2096+2097+ with app.test_request_context(...):2098+ generate_report()2099+2100+ When using the shell, it may be easier to push and pop the2101+ context manually to avoid indentation. ::2102+2103+ ctx = app.test_request_context(...)2104+ ctx.push()2105+ ...2106+ ctx.pop()2107+2108+ Takes the same arguments as Werkzeug's2109+ :class:`~werkzeug.test.EnvironBuilder`, with some defaults from2110+ the application. See the linked Werkzeug docs for most of the2111+ available arguments. Flask-specific behavior is listed here.2112+2113+ :param path: URL path being requested.2114+ :param base_url: Base URL where the app is being served, which2115+ ``path`` is relative to. If not given, built from2116+ :data:`PREFERRED_URL_SCHEME`, ``subdomain``,2117+ :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.2118+ :param subdomain: Subdomain name to append to2119+ :data:`SERVER_NAME`.2120+ :param url_scheme: Scheme to use instead of2121+ :data:`PREFERRED_URL_SCHEME`.2122+ :param data: The request body, either as a string or a dict of2123+ form keys and values.2124+ :param json: If given, this is serialized as JSON and passed as2125+ ``data``. Also defaults ``content_type`` to2126+ ``application/json``.2127+ :param args: other positional arguments passed to2128+ :class:`~werkzeug.test.EnvironBuilder`.2129+ :param kwargs: other keyword arguments passed to2130+ :class:`~werkzeug.test.EnvironBuilder`.2131+ """2132+ from .testing import EnvironBuilder2133+2134+ builder = EnvironBuilder(self, *args, **kwargs)2135+2136+ try:2137+ return self.request_context(builder.get_environ())2138+ finally:2139+ builder.close()2140+2141+ def wsgi_app(self, environ: dict, start_response: t.Callable) -> t.Any:2142+ """The actual WSGI application. This is not implemented in2143+ :meth:`__call__` so that middlewares can be applied without2144+ losing a reference to the app object. Instead of doing this::2145+2146+ app = MyMiddleware(app)2147+2148+ It's a better idea to do this instead::2149+2150+ app.wsgi_app = MyMiddleware(app.wsgi_app)2151+2152+ Then you still have the original application object around and2153+ can continue to call methods on it.2154+2155+ .. versionchanged:: 0.72156+ Teardown events for the request and app contexts are called2157+ even if an unhandled error occurs. Other events may not be2158+ called depending on when an error occurs during dispatch.2159+ See :ref:`callbacks-and-errors`.2160+2161+ :param environ: A WSGI environment.2162+ :param start_response: A callable accepting a status code,2163+ a list of headers, and an optional exception context to2164+ start the response.2165+ """2166+ ctx = self.request_context(environ)2167+ error: BaseException | None = None2168+ try:2169+ try:2170+ ctx.push()2171+ response = self.full_dispatch_request()2172+ except Exception as e:2173+ error = e2174+ response = self.handle_exception(e)2175+ except: # noqa: B0012176+ error = sys.exc_info()[1]2177+ raise2178+ return response(environ, start_response)2179+ finally:2180+ if "werkzeug.debug.preserve_context" in environ:2181+ environ["werkzeug.debug.preserve_context"](_cv_app.get())2182+ environ["werkzeug.debug.preserve_context"](_cv_request.get())2183+2184+ if error is not None and self.should_ignore_error(error):2185+ error = None2186+2187+ ctx.pop(error)2188+2189+ def __call__(self, environ: dict, start_response: t.Callable) -> t.Any:2190+ """The WSGI server calls the Flask application object as the2191+ WSGI application. This calls :meth:`wsgi_app`, which can be2192+ wrapped to apply middleware.2193+ """2194+ return self.wsgi_app(environ, start_response)added: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 Flask16+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: Flask,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: 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+ )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/scaffold.py+873 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 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_pathdeleted:src/flask/app.py-2194 removed
1-from __future__ import annotations2-3-import logging4-import os5-import sys6-import typing as t7-import weakref8-from collections.abc import Iterator as _abc_Iterator9-from datetime import timedelta10-from inspect import iscoroutinefunction11-from itertools import chain12-from types import TracebackType13-from urllib.parse import quote as _url_quote14-15-import click16-from werkzeug.datastructures import Headers17-from werkzeug.datastructures import ImmutableDict18-from werkzeug.exceptions import Aborter19-from werkzeug.exceptions import BadRequest20-from werkzeug.exceptions import BadRequestKeyError21-from werkzeug.exceptions import HTTPException22-from werkzeug.exceptions import InternalServerError23-from werkzeug.routing import BuildError24-from werkzeug.routing import Map25-from werkzeug.routing import MapAdapter26-from werkzeug.routing import RequestRedirect27-from werkzeug.routing import RoutingException28-from werkzeug.routing import Rule29-from werkzeug.serving import is_running_from_reloader30-from werkzeug.utils import cached_property31-from werkzeug.utils import redirect as _wz_redirect32-from werkzeug.wrappers import Response as BaseResponse33-34-from . import cli35-from . import typing as ft36-from .config import Config37-from .config import ConfigAttribute38-from .ctx import _AppCtxGlobals39-from .ctx import AppContext40-from .ctx import RequestContext41-from .globals import _cv_app42-from .globals import _cv_request43-from .globals import g44-from .globals import request45-from .globals import request_ctx46-from .globals import session47-from .helpers import _split_blueprint_path48-from .helpers import get_debug_flag49-from .helpers import get_flashed_messages50-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 setupmethod59-from .sessions import SecureCookieSessionInterface60-from .sessions import SessionInterface61-from .signals import appcontext_tearing_down62-from .signals import got_request_exception63-from .signals import request_finished64-from .signals import request_started65-from .signals import request_tearing_down66-from .templating import DispatchingJinjaLoader67-from .templating import Environment68-from .wrappers import Request69-from .wrappers import Response70-71-if t.TYPE_CHECKING: # pragma: no cover72- from .blueprints import Blueprint73- from .testing import FlaskClient74- from .testing import FlaskCliRunner75-76-T_shell_context_processor = t.TypeVar(77- "T_shell_context_processor", bound=ft.ShellContextProcessorCallable78-)79-T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)80-T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable)81-T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable)82-T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable)83-84-85-def _make_timedelta(value: timedelta | int | None) -> timedelta | None:86- if value is None or isinstance(value, timedelta):87- return value88-89- return timedelta(seconds=value)90-91-92-class Flask(Scaffold):93- """The flask object implements a WSGI application and acts as the central94- object. It is passed the name of the module or package of the95- application. Once it is created it will act as a central registry for96- the view functions, the URL rules, template configuration and much more.97-98- The name of the package is used to resolve resources from inside the99- package or the folder the module is contained in depending on if the100- package parameter resolves to an actual python package (a folder with101- an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).102-103- For more information about resource loading, see :func:`open_resource`.104-105- Usually you create a :class:`Flask` instance in your main module or106- in the :file:`__init__.py` file of your package like this::107-108- from flask import Flask109- app = Flask(__name__)110-111- .. admonition:: About the First Parameter112-113- The idea of the first parameter is to give Flask an idea of what114- belongs to your application. This name is used to find resources115- on the filesystem, can be used by extensions to improve debugging116- information and a lot more.117-118- So it's important what you provide there. If you are using a single119- module, `__name__` is always the correct value. If you however are120- using a package, it's usually recommended to hardcode the name of121- your package there.122-123- For example if your application is defined in :file:`yourapplication/app.py`124- you should create it with one of the two versions below::125-126- app = Flask('yourapplication')127- app = Flask(__name__.split('.')[0])128-129- Why is that? The application will work even with `__name__`, thanks130- to how resources are looked up. However it will make debugging more131- painful. Certain extensions can make assumptions based on the132- import name of your application. For example the Flask-SQLAlchemy133- extension will look for the code in your application that triggered134- an SQL query in debug mode. If the import name is not properly set135- up, that debugging information is lost. (For example it would only136- pick up SQL queries in `yourapplication.app` and not137- `yourapplication.views.frontend`)138-139- .. versionadded:: 0.7140- The `static_url_path`, `static_folder`, and `template_folder`141- parameters were added.142-143- .. versionadded:: 0.8144- The `instance_path` and `instance_relative_config` parameters were145- added.146-147- .. versionadded:: 0.11148- The `root_path` parameter was added.149-150- .. versionadded:: 1.0151- The ``host_matching`` and ``static_host`` parameters were added.152-153- .. versionadded:: 1.0154- The ``subdomain_matching`` parameter was added. Subdomain155- matching needs to be enabled manually now. Setting156- :data:`SERVER_NAME` does not implicitly enable it.157-158- :param import_name: the name of the application package159- :param static_url_path: can be used to specify a different path for the160- static files on the web. Defaults to the name161- of the `static_folder` folder.162- :param static_folder: The folder with static files that is served at163- ``static_url_path``. Relative to the application ``root_path``164- or an absolute path. Defaults to ``'static'``.165- :param static_host: the host to use when adding the static route.166- Defaults to None. Required when using ``host_matching=True``167- with a ``static_folder`` configured.168- :param host_matching: set ``url_map.host_matching`` attribute.169- Defaults to False.170- :param subdomain_matching: consider the subdomain relative to171- :data:`SERVER_NAME` when matching routes. Defaults to False.172- :param template_folder: the folder that contains the templates that should173- be used by the application. Defaults to174- ``'templates'`` folder in the root path of the175- application.176- :param instance_path: An alternative instance path for the application.177- By default the folder ``'instance'`` next to the178- package or module is assumed to be the instance179- path.180- :param instance_relative_config: if set to ``True`` relative filenames181- for loading the config are assumed to182- be relative to the instance path instead183- of the application root.184- :param root_path: The path to the root of the application files.185- This should only be set manually when it can't be detected186- automatically, such as for namespace packages.187- """188-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.294- default_config = ImmutableDict(295- {296- "DEBUG": None,297- "TESTING": False,298- "PROPAGATE_EXCEPTIONS": None,299- "SECRET_KEY": None,300- "PERMANENT_SESSION_LIFETIME": timedelta(days=31),301- "USE_X_SENDFILE": False,302- "SERVER_NAME": None,303- "APPLICATION_ROOT": "/",304- "SESSION_COOKIE_NAME": "session",305- "SESSION_COOKIE_DOMAIN": None,306- "SESSION_COOKIE_PATH": None,307- "SESSION_COOKIE_HTTPONLY": True,308- "SESSION_COOKIE_SECURE": False,309- "SESSION_COOKIE_SAMESITE": None,310- "SESSION_REFRESH_EACH_REQUEST": True,311- "MAX_CONTENT_LENGTH": None,312- "SEND_FILE_MAX_AGE_DEFAULT": None,313- "TRAP_BAD_REQUEST_ERRORS": None,314- "TRAP_HTTP_EXCEPTIONS": False,315- "EXPLAIN_TEMPLATE_LOADING": False,316- "PREFERRED_URL_SCHEME": "http",317- "TEMPLATES_AUTO_RELOAD": None,318- "MAX_COOKIE_SIZE": 4093,319- }320- )321-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 = Rule327-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 = Map333-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-348- #: the session interface to use. By default an instance of349- #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.350- #:351- #: .. versionadded:: 0.8352- session_interface: SessionInterface = SecureCookieSessionInterface()353-354- def __init__(355- self,356- import_name: str,357- static_url_path: str | None = None,358- static_folder: str | os.PathLike | None = "static",359- static_host: str | None = None,360- host_matching: bool = False,361- subdomain_matching: bool = False,362- template_folder: str | os.PathLike | None = "templates",363- instance_path: str | None = None,364- instance_relative_config: bool = False,365- root_path: str | None = None,366- ):367- super().__init__(368- import_name=import_name,369- static_folder=static_folder,370- static_url_path=static_url_path,371- template_folder=template_folder,372- root_path=root_path,373- )374-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-486- # Add a static route using the provided static_url_path, static_host,487- # and static_folder if there is a configured static_folder.488- # Note we do this without checking if static_folder exists.489- # For one, it might be created while the server is running (e.g. during490- # development). Also, Google App Engine stores static files somewhere491- if self.has_static_folder:492- assert (493- bool(static_host) == host_matching494- ), "Invalid static_host/host_matching combination"495- # Use a weakref to avoid creating a reference cycle between the app496- # and the view function (see #3761).497- self_ref = weakref.ref(self)498- self.add_url_rule(499- f"{self.static_url_path}/<path:filename>",500- endpoint="static",501- host=static_host,502- view_func=lambda **kw: self_ref().send_static_file(**kw), # type: ignore # noqa: B950503- )504-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.name508-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- )520-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.528-529- .. versionadded:: 0.8530- """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_name537-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`.542-543- In debug mode, the logger's :attr:`~logging.Logger.level` will544- be set to :data:`~logging.DEBUG`.545-546- If there are no handlers configured, a default handler will be547- added. See :doc:`/logging` for more information.548-549- .. versionchanged:: 1.1.0550- The logger takes the same name as :attr:`name` rather than551- hard-coding ``"flask.app"``.552-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.560-561- .. versionadded:: 0.3562- """563- return create_logger(self)564-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.572- """573- return self.create_jinja_environment()574-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.581-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)590-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.595-596- By default, this creates an instance of :attr:`aborter_class`,597- which defaults to :class:`werkzeug.exceptions.Aborter`.598-599- .. versionadded:: 2.2600- """601- return self.aborter_class()602-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.608-609- .. versionadded:: 0.8610- """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")615-616- def open_instance_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:617- """Opens a resource from the application's instance folder618- (:attr:`instance_path`). Otherwise works like619- :meth:`open_resource`. Instance resources can also be opened for620- writing.621-622- :param resource: the name of the resource. To access resources within623- subfolders use forward slashes as separator.624- :param mode: resource file opening mode, default is 'rb'.625- """626- return open(os.path.join(self.instance_path, resource), mode)627-628- def create_jinja_environment(self) -> Environment:629- """Create the Jinja environment based on :attr:`jinja_options`630- and the various Jinja-related methods of the app. Changing631- :attr:`jinja_options` after this will have no effect. Also adds632- Flask-related globals and filters to the environment.633-634- .. versionchanged:: 0.11635- ``Environment.auto_reload`` set in accordance with636- ``TEMPLATES_AUTO_RELOAD`` configuration option.637-638- .. versionadded:: 0.5639- """640- options = dict(self.jinja_options)641-642- if "autoescape" not in options:643- options["autoescape"] = self.select_jinja_autoescape644-645- if "auto_reload" not in options:646- auto_reload = self.config["TEMPLATES_AUTO_RELOAD"]647-648- if auto_reload is None:649- auto_reload = self.debug650-651- options["auto_reload"] = auto_reload652-653- rv = self.jinja_environment(self, **options)654- rv.globals.update(655- url_for=self.url_for,656- get_flashed_messages=get_flashed_messages,657- config=self.config,658- # request, session and g are normally added with the659- # context processor for efficiency reasons but for imported660- # templates we also want the proxies in there.661- request=request,662- session=session,663- g=g,664- )665- rv.policies["json.dumps_function"] = self.json.dumps666- return rv667-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.673-674- The global loader dispatches between the loaders of the application675- and the individual blueprints.676-677- .. versionadded:: 0.7678- """679- return DispatchingJinjaLoader(self)680-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`.684-685- .. versionchanged:: 2.2686- Autoescaping is now enabled by default for ``.svg`` files.687-688- .. versionadded:: 0.5689- """690- if filename is None:691- return True692- return filename.endswith((".html", ".htm", ".xml", ".xhtml", ".svg"))693-694- def update_template_context(self, context: dict) -> None:695- """Update the template context with some commonly used variables.696- This injects request, session, config and g into the template697- context as well as everything template context processors want698- to inject. Note that the as of Flask 0.6, the original values699- in the context will not be overridden if a context processor700- decides to return a value with the same key.701-702- :param context: the context as a dictionary that is updated in place703- to add extra variables.704- """705- names: t.Iterable[str | None] = (None,)706-707- # A template may be rendered outside a request context.708- if request:709- names = chain(names, reversed(request.blueprints))710-711- # The values passed to render_template take precedence. Keep a712- # copy to re-apply after all context functions.713- orig_ctx = context.copy()714-715- for name in names:716- if name in self.template_context_processors:717- for func in self.template_context_processors[name]:718- context.update(func())719-720- context.update(orig_ctx)721-722- def make_shell_context(self) -> dict:723- """Returns the shell context for an interactive shell for this724- application. This runs all the registered shell context725- processors.726-727- .. versionadded:: 0.11728- """729- rv = {"app": self, "g": g}730- for processor in self.shell_context_processors:731- rv.update(processor())732- return rv733-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-754- def run(755- self,756- host: str | None = None,757- port: int | None = None,758- debug: bool | None = None,759- load_dotenv: bool = True,760- **options: t.Any,761- ) -> None:762- """Runs the application on a local development server.763-764- Do not use ``run()`` in a production setting. It is not intended to765- meet security and performance requirements for a production server.766- Instead, see :doc:`/deploying/index` for WSGI server recommendations.767-768- If the :attr:`debug` flag is set the server will automatically reload769- for code changes and show a debugger in case an exception happened.770-771- If you want to run the application in debug mode, but disable the772- code execution on the interactive debugger, you can pass773- ``use_evalex=False`` as parameter. This will keep the debugger's774- traceback screen active, but disable code execution.775-776- It is not recommended to use this function for development with777- automatic reloading as this is badly supported. Instead you should778- be using the :command:`flask` command line script's ``run`` support.779-780- .. admonition:: Keep in Mind781-782- Flask will suppress any server error with a generic error page783- unless it is in debug mode. As such to enable just the784- interactive debugger without the code reloading, you have to785- invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.786- Setting ``use_debugger`` to ``True`` without being in debug mode787- won't catch any exceptions because there won't be any to788- catch.789-790- :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to791- have the server available externally as well. Defaults to792- ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable793- if present.794- :param port: the port of the webserver. Defaults to ``5000`` or the795- port defined in the ``SERVER_NAME`` config variable if present.796- :param debug: if given, enable or disable debug mode. See797- :attr:`debug`.798- :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`799- files to set environment variables. Will also change the working800- directory to the directory containing the first file found.801- :param options: the options to be forwarded to the underlying Werkzeug802- server. See :func:`werkzeug.serving.run_simple` for more803- information.804-805- .. versionchanged:: 1.0806- If installed, python-dotenv will be used to load environment807- variables from :file:`.env` and :file:`.flaskenv` files.808-809- The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.810-811- Threaded mode is enabled by default.812-813- .. versionchanged:: 0.10814- The default port is now picked from the ``SERVER_NAME``815- variable.816- """817- # Ignore this call so that it doesn't start another server if818- # the 'flask run' command is used.819- if os.environ.get("FLASK_RUN_FROM_CLI") == "true":820- if not is_running_from_reloader():821- click.secho(822- " * Ignoring a call to 'app.run()' that would block"823- " the current 'flask' CLI command.\n"824- " Only call 'app.run()' in an 'if __name__ =="825- ' "__main__"\' guard.',826- fg="red",827- )828-829- return830-831- if get_load_dotenv(load_dotenv):832- cli.load_dotenv()833-834- # if set, env var overrides existing value835- if "FLASK_DEBUG" in os.environ:836- self.debug = get_debug_flag()837-838- # debug passed to method overrides all other sources839- if debug is not None:840- self.debug = bool(debug)841-842- server_name = self.config.get("SERVER_NAME")843- sn_host = sn_port = None844-845- if server_name:846- sn_host, _, sn_port = server_name.partition(":")847-848- if not host:849- if sn_host:850- host = sn_host851- else:852- host = "127.0.0.1"853-854- if port or port == 0:855- port = int(port)856- elif sn_port:857- port = int(sn_port)858- else:859- port = 5000860-861- options.setdefault("use_reloader", self.debug)862- options.setdefault("use_debugger", self.debug)863- options.setdefault("threaded", True)864-865- cli.show_server_banner(self.debug, self.name)866-867- from werkzeug.serving import run_simple868-869- try:870- run_simple(t.cast(str, host), port, self, **options)871- finally:872- # reset the first request information if the development server873- # reset normally. This makes it possible to restart the server874- # without reloader and that stuff from an interactive shell.875- self._got_first_request = False876-877- def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> FlaskClient:878- """Creates a test client for this application. For information879- about unit testing head over to :doc:`/testing`.880-881- Note that if you are testing for assertions or exceptions in your882- application code, you must set ``app.testing = True`` in order for the883- exceptions to propagate to the test client. Otherwise, the exception884- will be handled by the application (not visible to the test client) and885- the only indication of an AssertionError or other exception will be a886- 500 status code response to the test client. See the :attr:`testing`887- attribute. For example::888-889- app.testing = True890- client = app.test_client()891-892- The test client can be used in a ``with`` block to defer the closing down893- of the context until the end of the ``with`` block. This is useful if894- you want to access the context locals for testing::895-896- with app.test_client() as c:897- rv = c.get('/?vodka=42')898- assert request.args['vodka'] == '42'899-900- Additionally, you may pass optional keyword arguments that will then901- be passed to the application's :attr:`test_client_class` constructor.902- For example::903-904- from flask.testing import FlaskClient905-906- class CustomClient(FlaskClient):907- def __init__(self, *args, **kwargs):908- self._authentication = kwargs.pop("authentication")909- super(CustomClient,self).__init__( *args, **kwargs)910-911- app.test_client_class = CustomClient912- client = app.test_client(authentication='Basic ....')913-914- See :class:`~flask.testing.FlaskClient` for more information.915-916- .. versionchanged:: 0.4917- added support for ``with`` block usage for the client.918-919- .. versionadded:: 0.7920- The `use_cookies` parameter was added as well as the ability921- to override the client to be used by setting the922- :attr:`test_client_class` attribute.923-924- .. versionchanged:: 0.11925- Added `**kwargs` to support passing additional keyword arguments to926- the constructor of :attr:`test_client_class`.927- """928- cls = self.test_client_class929- if cls is None:930- from .testing import FlaskClient as cls931- return cls( # type: ignore932- self, self.response_class, use_cookies=use_cookies, **kwargs933- )934-935- def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner:936- """Create a CLI runner for testing CLI commands.937- See :ref:`testing-cli`.938-939- Returns an instance of :attr:`test_cli_runner_class`, by default940- :class:`~flask.testing.FlaskCliRunner`. The Flask app object is941- passed as the first argument.942-943- .. versionadded:: 1.0944- """945- cls = self.test_cli_runner_class946-947- if cls is None:948- from .testing import FlaskCliRunner as cls949-950- return cls(self, **kwargs) # type: ignore951-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-1229- def handle_http_exception(1230- self, e: HTTPException1231- ) -> HTTPException | ft.ResponseReturnValue:1232- """Handles an HTTP exception. By default this will invoke the1233- registered error handlers and fall back to returning the1234- exception as response.1235-1236- .. versionchanged:: 1.0.31237- ``RoutingException``, used internally for actions such as1238- slash redirects during routing, is not passed to error1239- handlers.1240-1241- .. versionchanged:: 1.01242- Exceptions are looked up by code *and* by MRO, so1243- ``HTTPException`` subclasses can be handled with a catch-all1244- handler for the base ``HTTPException``.1245-1246- .. versionadded:: 0.31247- """1248- # Proxy exceptions don't have error codes. We want to always return1249- # those unchanged as errors1250- if e.code is None:1251- return e1252-1253- # RoutingExceptions are used internally to trigger routing1254- # actions, such as slash redirects raising RequestRedirect. They1255- # are not raised or handled in user code.1256- if isinstance(e, RoutingException):1257- return e1258-1259- handler = self._find_error_handler(e)1260- if handler is None:1261- return e1262- return self.ensure_sync(handler)(e)1263-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-1299- def handle_user_exception(1300- self, e: Exception1301- ) -> HTTPException | ft.ResponseReturnValue:1302- """This method is called whenever an exception occurs that1303- should be handled. A special case is :class:`~werkzeug1304- .exceptions.HTTPException` which is forwarded to the1305- :meth:`handle_http_exception` method. This function will either1306- return a response value or reraise the exception with the same1307- traceback.1308-1309- .. versionchanged:: 1.01310- Key errors raised from request data like ``form`` show the1311- bad key in debug mode rather than a generic bad request1312- message.1313-1314- .. versionadded:: 0.71315- """1316- if isinstance(e, BadRequestKeyError) and (1317- self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]1318- ):1319- e.show_exception = True1320-1321- if isinstance(e, HTTPException) and not self.trap_http_exception(e):1322- return self.handle_http_exception(e)1323-1324- handler = self._find_error_handler(e)1325-1326- if handler is None:1327- raise1328-1329- return self.ensure_sync(handler)(e)1330-1331- def handle_exception(self, e: Exception) -> Response:1332- """Handle an exception that did not have an error handler1333- associated with it, or that was raised from an error handler.1334- This always causes a 500 ``InternalServerError``.1335-1336- Always sends the :data:`got_request_exception` signal.1337-1338- If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug1339- mode, the error will be re-raised so that the debugger can1340- display it. Otherwise, the original exception is logged, and1341- an :exc:`~werkzeug.exceptions.InternalServerError` is returned.1342-1343- If an error handler is registered for ``InternalServerError`` or1344- ``500``, it will be used. For consistency, the handler will1345- always receive the ``InternalServerError``. The original1346- unhandled exception is available as ``e.original_exception``.1347-1348- .. versionchanged:: 1.1.01349- Always passes the ``InternalServerError`` instance to the1350- handler, setting ``original_exception`` to the unhandled1351- error.1352-1353- .. versionchanged:: 1.1.01354- ``after_request`` functions and other finalization is done1355- even for the default 500 response when there is no handler.1356-1357- .. versionadded:: 0.31358- """1359- exc_info = sys.exc_info()1360- got_request_exception.send(self, _async_wrapper=self.ensure_sync, exception=e)1361- propagate = self.config["PROPAGATE_EXCEPTIONS"]1362-1363- if propagate is None:1364- propagate = self.testing or self.debug1365-1366- if propagate:1367- # Re-raise if called with an active exception, otherwise1368- # raise the passed in exception.1369- if exc_info[1] is e:1370- raise1371-1372- raise e1373-1374- self.log_exception(exc_info)1375- server_error: InternalServerError | ft.ResponseReturnValue1376- server_error = InternalServerError(original_exception=e)1377- handler = self._find_error_handler(server_error)1378-1379- if handler is not None:1380- server_error = self.ensure_sync(handler)(server_error)1381-1382- return self.finalize_request(server_error, from_error_handler=True)1383-1384- def log_exception(1385- self,1386- exc_info: (tuple[type, BaseException, TracebackType] | tuple[None, None, None]),1387- ) -> None:1388- """Logs an exception. This is called by :meth:`handle_exception`1389- if debugging is disabled and right before the handler is called.1390- The default implementation logs the exception as error on the1391- :attr:`logger`.1392-1393- .. versionadded:: 0.81394- """1395- self.logger.error(1396- f"Exception on {request.path} [{request.method}]", exc_info=exc_info1397- )1398-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-1427- def dispatch_request(self) -> ft.ResponseReturnValue:1428- """Does the request dispatching. Matches the URL and returns the1429- return value of the view or error handler. This does not have to1430- be a response object. In order to convert the return value to a1431- proper response object, call :func:`make_response`.1432-1433- .. versionchanged:: 0.71434- This no longer does the exception handling, this code was1435- moved to the new :meth:`full_dispatch_request`.1436- """1437- req = request_ctx.request1438- if req.routing_exception is not None:1439- self.raise_routing_exception(req)1440- rule: Rule = req.url_rule # type: ignore[assignment]1441- # if we provide automatic options for this URL and the1442- # request came with the OPTIONS method, reply automatically1443- if (1444- getattr(rule, "provide_automatic_options", False)1445- and req.method == "OPTIONS"1446- ):1447- return self.make_default_options_response()1448- # otherwise dispatch to the handler for that endpoint1449- view_args: dict[str, t.Any] = req.view_args # type: ignore[assignment]1450- return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)1451-1452- def full_dispatch_request(self) -> Response:1453- """Dispatches the request and on top of that performs request1454- pre and postprocessing as well as HTTP exception catching and1455- error handling.1456-1457- .. versionadded:: 0.71458- """1459- self._got_first_request = True1460-1461- try:1462- request_started.send(self, _async_wrapper=self.ensure_sync)1463- rv = self.preprocess_request()1464- if rv is None:1465- rv = self.dispatch_request()1466- except Exception as e:1467- rv = self.handle_user_exception(e)1468- return self.finalize_request(rv)1469-1470- def finalize_request(1471- self,1472- rv: ft.ResponseReturnValue | HTTPException,1473- from_error_handler: bool = False,1474- ) -> Response:1475- """Given the return value from a view function this finalizes1476- the request by converting it into a response and invoking the1477- postprocessing functions. This is invoked for both normal1478- request dispatching as well as error handlers.1479-1480- Because this means that it might be called as a result of a1481- failure a special safe mode is available which can be enabled1482- with the `from_error_handler` flag. If enabled, failures in1483- response processing will be logged and otherwise ignored.1484-1485- :internal:1486- """1487- response = self.make_response(rv)1488- try:1489- response = self.process_response(response)1490- request_finished.send(1491- self, _async_wrapper=self.ensure_sync, response=response1492- )1493- except Exception:1494- if not from_error_handler:1495- raise1496- self.logger.exception(1497- "Request finalizing failed with an error while handling an error"1498- )1499- return response1500-1501- def make_default_options_response(self) -> Response:1502- """This method is called to create the default ``OPTIONS`` response.1503- This can be changed through subclassing to change the default1504- behavior of ``OPTIONS`` responses.1505-1506- .. versionadded:: 0.71507- """1508- adapter = request_ctx.url_adapter1509- methods = adapter.allowed_methods() # type: ignore[union-attr]1510- rv = self.response_class()1511- rv.allow.update(methods)1512- return rv1513-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-1524- def ensure_sync(self, func: t.Callable) -> t.Callable:1525- """Ensure that the function is synchronous for WSGI workers.1526- Plain ``def`` functions are returned as-is. ``async def``1527- functions are wrapped to run and wait for the response.1528-1529- Override this method to change how the app runs async views.1530-1531- .. versionadded:: 2.01532- """1533- if iscoroutinefunction(func):1534- return self.async_to_sync(func)1535-1536- return func1537-1538- def async_to_sync(1539- self, func: t.Callable[..., t.Coroutine]1540- ) -> t.Callable[..., t.Any]:1541- """Return a sync function that will run the coroutine function.1542-1543- .. code-block:: python1544-1545- result = app.async_to_sync(func)(*args, **kwargs)1546-1547- Override this method to change how the app converts async code1548- to be synchronously callable.1549-1550- .. versionadded:: 2.01551- """1552- try:1553- from asgiref.sync import async_to_sync as asgiref_async_to_sync1554- except ImportError:1555- raise RuntimeError(1556- "Install Flask with the 'async' extra in order to use async views."1557- ) from None1558-1559- return asgiref_async_to_sync(func)1560-1561- def url_for(1562- self,1563- endpoint: str,1564- *,1565- _anchor: str | None = None,1566- _method: str | None = None,1567- _scheme: str | None = None,1568- _external: bool | None = None,1569- **values: t.Any,1570- ) -> str:1571- """Generate a URL to the given endpoint with the given values.1572-1573- This is called by :func:`flask.url_for`, and can be called1574- directly as well.1575-1576- An *endpoint* is the name of a URL rule, usually added with1577- :meth:`@app.route() <route>`, and usually the same name as the1578- view function. A route defined in a :class:`~flask.Blueprint`1579- will prepend the blueprint's name separated by a ``.`` to the1580- endpoint.1581-1582- In some cases, such as email messages, you want URLs to include1583- the scheme and domain, like ``https://example.com/hello``. When1584- not in an active request, URLs will be external by default, but1585- this requires setting :data:`SERVER_NAME` so Flask knows what1586- domain to use. :data:`APPLICATION_ROOT` and1587- :data:`PREFERRED_URL_SCHEME` should also be configured as1588- needed. This config is only used when not in an active request.1589-1590- Functions can be decorated with :meth:`url_defaults` to modify1591- keyword arguments before the URL is built.1592-1593- If building fails for some reason, such as an unknown endpoint1594- or incorrect values, the app's :meth:`handle_url_build_error`1595- method is called. If that returns a string, that is returned,1596- otherwise a :exc:`~werkzeug.routing.BuildError` is raised.1597-1598- :param endpoint: The endpoint name associated with the URL to1599- generate. If this starts with a ``.``, the current blueprint1600- name (if any) will be used.1601- :param _anchor: If given, append this as ``#anchor`` to the URL.1602- :param _method: If given, generate the URL associated with this1603- method for the endpoint.1604- :param _scheme: If given, the URL will have this scheme if it1605- is external.1606- :param _external: If given, prefer the URL to be internal1607- (False) or require it to be external (True). External URLs1608- include the scheme and domain. When not in an active1609- request, URLs are external by default.1610- :param values: Values to use for the variable parts of the URL1611- rule. Unknown keys are appended as query string arguments,1612- like ``?a=b&c=d``.1613-1614- .. versionadded:: 2.21615- Moved from ``flask.url_for``, which calls this method.1616- """1617- req_ctx = _cv_request.get(None)1618-1619- if req_ctx is not None:1620- url_adapter = req_ctx.url_adapter1621- blueprint_name = req_ctx.request.blueprint1622-1623- # If the endpoint starts with "." and the request matches a1624- # blueprint, the endpoint is relative to the blueprint.1625- if endpoint[:1] == ".":1626- if blueprint_name is not None:1627- endpoint = f"{blueprint_name}{endpoint}"1628- else:1629- endpoint = endpoint[1:]1630-1631- # When in a request, generate a URL without scheme and1632- # domain by default, unless a scheme is given.1633- if _external is None:1634- _external = _scheme is not None1635- else:1636- app_ctx = _cv_app.get(None)1637-1638- # If called by helpers.url_for, an app context is active,1639- # use its url_adapter. Otherwise, app.url_for was called1640- # directly, build an adapter.1641- if app_ctx is not None:1642- url_adapter = app_ctx.url_adapter1643- else:1644- url_adapter = self.create_url_adapter(None)1645-1646- if url_adapter is None:1647- raise RuntimeError(1648- "Unable to build URLs outside an active request"1649- " without 'SERVER_NAME' configured. Also configure"1650- " 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as"1651- " needed."1652- )1653-1654- # When outside a request, generate a URL with scheme and1655- # domain by default.1656- if _external is None:1657- _external = True1658-1659- # It is an error to set _scheme when _external=False, in order1660- # to avoid accidental insecure URLs.1661- if _scheme is not None and not _external:1662- raise ValueError("When specifying '_scheme', '_external' must be True.")1663-1664- self.inject_url_defaults(endpoint, values)1665-1666- try:1667- rv = url_adapter.build( # type: ignore[union-attr]1668- endpoint,1669- values,1670- method=_method,1671- url_scheme=_scheme,1672- force_external=_external,1673- )1674- except BuildError as error:1675- values.update(1676- _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external1677- )1678- return self.handle_url_build_error(error, endpoint, values)1679-1680- if _anchor is not None:1681- _anchor = _url_quote(_anchor, safe="%!#$&'()*+,/:;=?@")1682- rv = f"{rv}#{_anchor}"1683-1684- return rv1685-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-1700- def make_response(self, rv: ft.ResponseReturnValue) -> Response:1701- """Convert the return value from a view function to an instance of1702- :attr:`response_class`.1703-1704- :param rv: the return value from the view function. The view function1705- must return a response. Returning ``None``, or the view ending1706- without returning, is not allowed. The following types are allowed1707- for ``view_rv``:1708-1709- ``str``1710- A response object is created with the string encoded to UTF-81711- as the body.1712-1713- ``bytes``1714- A response object is created with the bytes as the body.1715-1716- ``dict``1717- A dictionary that will be jsonify'd before being returned.1718-1719- ``list``1720- A list that will be jsonify'd before being returned.1721-1722- ``generator`` or ``iterator``1723- A generator that returns ``str`` or ``bytes`` to be1724- streamed as the response.1725-1726- ``tuple``1727- Either ``(body, status, headers)``, ``(body, status)``, or1728- ``(body, headers)``, where ``body`` is any of the other types1729- allowed here, ``status`` is a string or an integer, and1730- ``headers`` is a dictionary or a list of ``(key, value)``1731- tuples. If ``body`` is a :attr:`response_class` instance,1732- ``status`` overwrites the exiting value and ``headers`` are1733- extended.1734-1735- :attr:`response_class`1736- The object is returned unchanged.1737-1738- other :class:`~werkzeug.wrappers.Response` class1739- The object is coerced to :attr:`response_class`.1740-1741- :func:`callable`1742- The function is called as a WSGI application. The result is1743- used to create a response object.1744-1745- .. versionchanged:: 2.21746- A generator will be converted to a streaming response.1747- A list will be converted to a JSON response.1748-1749- .. versionchanged:: 1.11750- A dict will be converted to a JSON response.1751-1752- .. versionchanged:: 0.91753- Previously a tuple was interpreted as the arguments for the1754- response object.1755- """1756-1757- status = headers = None1758-1759- # unpack tuple returns1760- if isinstance(rv, tuple):1761- len_rv = len(rv)1762-1763- # a 3-tuple is unpacked directly1764- if len_rv == 3:1765- rv, status, headers = rv # type: ignore[misc]1766- # decide if a 2-tuple has status or headers1767- elif len_rv == 2:1768- if isinstance(rv[1], (Headers, dict, tuple, list)):1769- rv, headers = rv1770- else:1771- rv, status = rv # type: ignore[assignment,misc]1772- # other sized tuples are not allowed1773- else:1774- raise TypeError(1775- "The view function did not return a valid response tuple."1776- " The tuple must have the form (body, status, headers),"1777- " (body, status), or (body, headers)."1778- )1779-1780- # the body must not be None1781- if rv is None:1782- raise TypeError(1783- f"The view function for {request.endpoint!r} did not"1784- " return a valid response. The function either returned"1785- " None or ended without a return statement."1786- )1787-1788- # make sure the body is an instance of the response class1789- if not isinstance(rv, self.response_class):1790- if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, _abc_Iterator):1791- # let the response class set the status and headers instead of1792- # waiting to do it manually, so that the class can handle any1793- # special logic1794- rv = self.response_class(1795- rv,1796- status=status,1797- headers=headers, # type: ignore[arg-type]1798- )1799- status = headers = None1800- elif isinstance(rv, (dict, list)):1801- rv = self.json.response(rv)1802- elif isinstance(rv, BaseResponse) or callable(rv):1803- # evaluate a WSGI callable, or coerce a different response1804- # class to the correct type1805- try:1806- rv = self.response_class.force_type(1807- rv, request.environ # type: ignore[arg-type]1808- )1809- except TypeError as e:1810- raise TypeError(1811- f"{e}\nThe view function did not return a valid"1812- " response. The return type must be a string,"1813- " dict, list, tuple with headers or status,"1814- " Response instance, or WSGI callable, but it"1815- f" was a {type(rv).__name__}."1816- ).with_traceback(sys.exc_info()[2]) from None1817- else:1818- raise TypeError(1819- "The view function did not return a valid"1820- " response. The return type must be a string,"1821- " dict, list, tuple with headers or status,"1822- " Response instance, or WSGI callable, but it was a"1823- f" {type(rv).__name__}."1824- )1825-1826- rv = t.cast(Response, rv)1827- # prefer the status if it was provided1828- if status is not None:1829- if isinstance(status, (str, bytes, bytearray)):1830- rv.status = status1831- else:1832- rv.status_code = status1833-1834- # extend existing headers with provided headers1835- if headers:1836- rv.headers.update(headers) # type: ignore[arg-type]1837-1838- return rv1839-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-1935- def preprocess_request(self) -> ft.ResponseReturnValue | None:1936- """Called before the request is dispatched. Calls1937- :attr:`url_value_preprocessors` registered with the app and the1938- current blueprint (if any). Then calls :attr:`before_request_funcs`1939- registered with the app and the blueprint.1940-1941- If any :meth:`before_request` handler returns a non-None value, the1942- value is handled as if it was the return value from the view, and1943- further request handling is stopped.1944- """1945- names = (None, *reversed(request.blueprints))1946-1947- for name in names:1948- if name in self.url_value_preprocessors:1949- for url_func in self.url_value_preprocessors[name]:1950- url_func(request.endpoint, request.view_args)1951-1952- for name in names:1953- if name in self.before_request_funcs:1954- for before_func in self.before_request_funcs[name]:1955- rv = self.ensure_sync(before_func)()1956-1957- if rv is not None:1958- return rv1959-1960- return None1961-1962- def process_response(self, response: Response) -> Response:1963- """Can be overridden in order to modify the response object1964- before it's sent to the WSGI server. By default this will1965- call all the :meth:`after_request` decorated functions.1966-1967- .. versionchanged:: 0.51968- As of Flask 0.5 the functions registered for after request1969- execution are called in reverse order of registration.1970-1971- :param response: a :attr:`response_class` object.1972- :return: a new response object or the same, has to be an1973- instance of :attr:`response_class`.1974- """1975- ctx = request_ctx._get_current_object() # type: ignore[attr-defined]1976-1977- for func in ctx._after_request_functions:1978- response = self.ensure_sync(func)(response)1979-1980- for name in chain(request.blueprints, (None,)):1981- if name in self.after_request_funcs:1982- for func in reversed(self.after_request_funcs[name]):1983- response = self.ensure_sync(func)(response)1984-1985- if not self.session_interface.is_null_session(ctx.session):1986- self.session_interface.save_session(self, ctx.session, response)1987-1988- return response1989-1990- def do_teardown_request(1991- self, exc: BaseException | None = _sentinel # type: ignore1992- ) -> None:1993- """Called after the request is dispatched and the response is1994- returned, right before the request context is popped.1995-1996- This calls all functions decorated with1997- :meth:`teardown_request`, and :meth:`Blueprint.teardown_request`1998- if a blueprint handled the request. Finally, the1999- :data:`request_tearing_down` signal is sent.2000-2001- This is called by2002- :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`,2003- which may be delayed during testing to maintain access to2004- resources.2005-2006- :param exc: An unhandled exception raised while dispatching the2007- request. Detected from the current exception information if2008- not passed. Passed to each teardown function.2009-2010- .. versionchanged:: 0.92011- Added the ``exc`` argument.2012- """2013- if exc is _sentinel:2014- exc = sys.exc_info()[1]2015-2016- for name in chain(request.blueprints, (None,)):2017- if name in self.teardown_request_funcs:2018- for func in reversed(self.teardown_request_funcs[name]):2019- self.ensure_sync(func)(exc)2020-2021- request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)2022-2023- def do_teardown_appcontext(2024- self, exc: BaseException | None = _sentinel # type: ignore2025- ) -> None:2026- """Called right before the application context is popped.2027-2028- When handling a request, the application context is popped2029- after the request context. See :meth:`do_teardown_request`.2030-2031- This calls all functions decorated with2032- :meth:`teardown_appcontext`. Then the2033- :data:`appcontext_tearing_down` signal is sent.2034-2035- This is called by2036- :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.2037-2038- .. versionadded:: 0.92039- """2040- if exc is _sentinel:2041- exc = sys.exc_info()[1]2042-2043- for func in reversed(self.teardown_appcontext_funcs):2044- self.ensure_sync(func)(exc)2045-2046- appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)2047-2048- def app_context(self) -> AppContext:2049- """Create an :class:`~flask.ctx.AppContext`. Use as a ``with``2050- block to push the context, which will make :data:`current_app`2051- point at this application.2052-2053- An application context is automatically pushed by2054- :meth:`RequestContext.push() <flask.ctx.RequestContext.push>`2055- when handling a request, and when running a CLI command. Use2056- this to manually create a context outside of these situations.2057-2058- ::2059-2060- with app.app_context():2061- init_db()2062-2063- See :doc:`/appcontext`.2064-2065- .. versionadded:: 0.92066- """2067- return AppContext(self)2068-2069- def request_context(self, environ: dict) -> RequestContext:2070- """Create a :class:`~flask.ctx.RequestContext` representing a2071- WSGI environment. Use a ``with`` block to push the context,2072- which will make :data:`request` point at this request.2073-2074- See :doc:`/reqcontext`.2075-2076- Typically you should not call this from your own code. A request2077- context is automatically pushed by the :meth:`wsgi_app` when2078- handling a request. Use :meth:`test_request_context` to create2079- an environment and context instead of this method.2080-2081- :param environ: a WSGI environment2082- """2083- return RequestContext(self, environ)2084-2085- def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> RequestContext:2086- """Create a :class:`~flask.ctx.RequestContext` for a WSGI2087- environment created from the given values. This is mostly useful2088- during testing, where you may want to run a function that uses2089- request data without dispatching a full request.2090-2091- See :doc:`/reqcontext`.2092-2093- Use a ``with`` block to push the context, which will make2094- :data:`request` point at the request for the created2095- environment. ::2096-2097- with app.test_request_context(...):2098- generate_report()2099-2100- When using the shell, it may be easier to push and pop the2101- context manually to avoid indentation. ::2102-2103- ctx = app.test_request_context(...)2104- ctx.push()2105- ...2106- ctx.pop()2107-2108- Takes the same arguments as Werkzeug's2109- :class:`~werkzeug.test.EnvironBuilder`, with some defaults from2110- the application. See the linked Werkzeug docs for most of the2111- available arguments. Flask-specific behavior is listed here.2112-2113- :param path: URL path being requested.2114- :param base_url: Base URL where the app is being served, which2115- ``path`` is relative to. If not given, built from2116- :data:`PREFERRED_URL_SCHEME`, ``subdomain``,2117- :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.2118- :param subdomain: Subdomain name to append to2119- :data:`SERVER_NAME`.2120- :param url_scheme: Scheme to use instead of2121- :data:`PREFERRED_URL_SCHEME`.2122- :param data: The request body, either as a string or a dict of2123- form keys and values.2124- :param json: If given, this is serialized as JSON and passed as2125- ``data``. Also defaults ``content_type`` to2126- ``application/json``.2127- :param args: other positional arguments passed to2128- :class:`~werkzeug.test.EnvironBuilder`.2129- :param kwargs: other keyword arguments passed to2130- :class:`~werkzeug.test.EnvironBuilder`.2131- """2132- from .testing import EnvironBuilder2133-2134- builder = EnvironBuilder(self, *args, **kwargs)2135-2136- try:2137- return self.request_context(builder.get_environ())2138- finally:2139- builder.close()2140-2141- def wsgi_app(self, environ: dict, start_response: t.Callable) -> t.Any:2142- """The actual WSGI application. This is not implemented in2143- :meth:`__call__` so that middlewares can be applied without2144- losing a reference to the app object. Instead of doing this::2145-2146- app = MyMiddleware(app)2147-2148- It's a better idea to do this instead::2149-2150- app.wsgi_app = MyMiddleware(app.wsgi_app)2151-2152- Then you still have the original application object around and2153- can continue to call methods on it.2154-2155- .. versionchanged:: 0.72156- Teardown events for the request and app contexts are called2157- even if an unhandled error occurs. Other events may not be2158- called depending on when an error occurs during dispatch.2159- See :ref:`callbacks-and-errors`.2160-2161- :param environ: A WSGI environment.2162- :param start_response: A callable accepting a status code,2163- a list of headers, and an optional exception context to2164- start the response.2165- """2166- ctx = self.request_context(environ)2167- error: BaseException | None = None2168- try:2169- try:2170- ctx.push()2171- response = self.full_dispatch_request()2172- except Exception as e:2173- error = e2174- response = self.handle_exception(e)2175- except: # noqa: B0012176- error = sys.exc_info()[1]2177- raise2178- return response(environ, start_response)2179- finally:2180- if "werkzeug.debug.preserve_context" in environ:2181- environ["werkzeug.debug.preserve_context"](_cv_app.get())2182- environ["werkzeug.debug.preserve_context"](_cv_request.get())2183-2184- if error is not None and self.should_ignore_error(error):2185- error = None2186-2187- ctx.pop(error)2188-2189- def __call__(self, environ: dict, start_response: t.Callable) -> t.Any:2190- """The WSGI server calls the Flask application object as the2191- WSGI application. This calls :meth:`wsgi_app`, which can be2192- wrapped to apply middleware.2193- """2194- return self.wsgi_app(environ, start_response)deleted:src/flask/blueprints.py-626 removed
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 Flask16-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: Flask,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: 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- )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 fdeleted: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_path