Skip to content
Myr

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

6 files+3693 added−3693 removed

added:src/flask/sansio/app.py+2194 added
1from __future__ import annotations23import logging4import os5import sys6import typing as t7import weakref8from collections.abc import Iterator as _abc_Iterator9from datetime import timedelta10from inspect import iscoroutinefunction11from itertools import chain12from types import TracebackType13from urllib.parse import quote as _url_quote1415import click16from werkzeug.datastructures import Headers17from werkzeug.datastructures import ImmutableDict18from werkzeug.exceptions import Aborter19from werkzeug.exceptions import BadRequest20from werkzeug.exceptions import BadRequestKeyError21from werkzeug.exceptions import HTTPException22from werkzeug.exceptions import InternalServerError23from werkzeug.routing import BuildError24from werkzeug.routing import Map25from werkzeug.routing import MapAdapter26from werkzeug.routing import RequestRedirect27from werkzeug.routing import RoutingException28from werkzeug.routing import Rule29from werkzeug.serving import is_running_from_reloader30from werkzeug.utils import cached_property31from werkzeug.utils import redirect as _wz_redirect32from werkzeug.wrappers import Response as BaseResponse3334from . import cli35from . import typing as ft36from .config import Config37from .config import ConfigAttribute38from .ctx import _AppCtxGlobals39from .ctx import AppContext40from .ctx import RequestContext41from .globals import _cv_app42from .globals import _cv_request43from .globals import g44from .globals import request45from .globals import request_ctx46from .globals import session47from .helpers import _split_blueprint_path48from .helpers import get_debug_flag49from .helpers import get_flashed_messages50from .helpers import get_load_dotenv51from .json.provider import DefaultJSONProvider52from .json.provider import JSONProvider53from .logging import create_logger54from .scaffold import _endpoint_from_view_func55from .scaffold import _sentinel56from .scaffold import find_package57from .scaffold import Scaffold58from .scaffold import setupmethod59from .sessions import SecureCookieSessionInterface60from .sessions import SessionInterface61from .signals import appcontext_tearing_down62from .signals import got_request_exception63from .signals import request_finished64from .signals import request_started65from .signals import request_tearing_down66from .templating import DispatchingJinjaLoader67from .templating import Environment68from .wrappers import Request69from .wrappers import Response7071if t.TYPE_CHECKING: # pragma: no cover72 from .blueprints import Blueprint73 from .testing import FlaskClient74 from .testing import FlaskCliRunner7576T_shell_context_processor = t.TypeVar(77 "T_shell_context_processor", bound=ft.ShellContextProcessorCallable78)79T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)80T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable)81T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable)82T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable)838485def _make_timedelta(value: timedelta | int | None) -> timedelta | None:86 if value is None or isinstance(value, timedelta):87 return value8889 return timedelta(seconds=value)909192class 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.9798 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).102103 For more information about resource loading, see :func:`open_resource`.104105 Usually you create a :class:`Flask` instance in your main module or106 in the :file:`__init__.py` file of your package like this::107108 from flask import Flask109 app = Flask(__name__)110111 .. admonition:: About the First Parameter112113 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.117118 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.122123 For example if your application is defined in :file:`yourapplication/app.py`124 you should create it with one of the two versions below::125126 app = Flask('yourapplication')127 app = Flask(__name__.split('.')[0])128129 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`)138139 .. versionadded:: 0.7140 The `static_url_path`, `static_folder`, and `template_folder`141 parameters were added.142143 .. versionadded:: 0.8144 The `instance_path` and `instance_relative_config` parameters were145 added.146147 .. versionadded:: 0.11148 The `root_path` parameter was added.149150 .. versionadded:: 1.0151 The ``host_matching`` and ``static_host`` parameters were added.152153 .. 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.157158 :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 """188189 #: The class that is used for request objects. See :class:`~flask.Request`190 #: for more information.191 request_class = Request192193 #: The class that is used for response objects. See194 #: :class:`~flask.Response` for more information.195 response_class = Response196197 #: 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 = Aborter206207 #: The class that is used for the Jinja environment.208 #:209 #: .. versionadded:: 0.11210 jinja_environment = Environment211212 #: 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 = _AppCtxGlobals227228 #: 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 = Config238239 #: 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")250251 #: 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")258259 #: 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 )269270 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.274275 The default, :class:`~flask.json.provider.DefaultJSONProvider`, uses276 Python's built-in :mod:`json` library. A different provider can use277 a different JSON library.278279 .. versionadded:: 2.2280 """281282 #: 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 = {}292293 #: 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 )321322 #: 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 = Rule327328 #: 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 = Map333334 #: 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 = None339340 #: 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 = None347348 #: 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()353354 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 )374375 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 )382383 #: Holds the path to the instance folder.384 #:385 #: .. versionadded:: 0.8386 self.instance_path = instance_path387388 #: 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)392393 #: 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()400401 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.405406 An instance of :attr:`json_provider_class`. Can be customized by407 changing that attribute on a subclass, or by assigning to this408 attribute afterwards.409410 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.413414 .. versionadded:: 2.2415 """416417 #: 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 ] = []428429 #: 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] = []436437 #: 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] = []442443 #: 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] = {}450451 #: 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 = {}461462 #: 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()478479 self.url_map.host_matching = host_matching480 self.subdomain_matching = subdomain_matching481482 # tracks internally if the application already handled at least one483 # request.484 self._got_first_request = False485486 # 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 )504505 # 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.name508509 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 )520521 @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.528529 .. 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_name537538 @cached_property539 def logger(self) -> logging.Logger:540 """A standard Python :class:`~logging.Logger` for the app, with541 the same name as :attr:`name`.542543 In debug mode, the logger's :attr:`~logging.Logger.level` will544 be set to :data:`~logging.DEBUG`.545546 If there are no handlers configured, a default handler will be547 added. See :doc:`/logging` for more information.548549 .. versionchanged:: 1.1.0550 The logger takes the same name as :attr:`name` rather than551 hard-coding ``"flask.app"``.552553 .. 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.560561 .. versionadded:: 0.3562 """563 return create_logger(self)564565 @cached_property566 def jinja_env(self) -> Environment:567 """The Jinja environment used to load templates.568569 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()574575 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.581582 .. 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)590591 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.595596 By default, this creates an instance of :attr:`aborter_class`,597 which defaults to :class:`werkzeug.exceptions.Aborter`.598599 .. versionadded:: 2.2600 """601 return self.aborter_class()602603 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.608609 .. 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")615616 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.621622 :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)627628 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.633634 .. versionchanged:: 0.11635 ``Environment.auto_reload`` set in accordance with636 ``TEMPLATES_AUTO_RELOAD`` configuration option.637638 .. versionadded:: 0.5639 """640 options = dict(self.jinja_options)641642 if "autoescape" not in options:643 options["autoescape"] = self.select_jinja_autoescape644645 if "auto_reload" not in options:646 auto_reload = self.config["TEMPLATES_AUTO_RELOAD"]647648 if auto_reload is None:649 auto_reload = self.debug650651 options["auto_reload"] = auto_reload652653 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 rv667668 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.673674 The global loader dispatches between the loaders of the application675 and the individual blueprints.676677 .. versionadded:: 0.7678 """679 return DispatchingJinjaLoader(self)680681 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`.684685 .. versionchanged:: 2.2686 Autoescaping is now enabled by default for ``.svg`` files.687688 .. versionadded:: 0.5689 """690 if filename is None:691 return True692 return filename.endswith((".html", ".htm", ".xml", ".xhtml", ".svg"))693694 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.701702 :param context: the context as a dictionary that is updated in place703 to add extra variables.704 """705 names: t.Iterable[str | None] = (None,)706707 # A template may be rendered outside a request context.708 if request:709 names = chain(names, reversed(request.blueprints))710711 # The values passed to render_template take precedence. Keep a712 # copy to re-apply after all context functions.713 orig_ctx = context.copy()714715 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())719720 context.update(orig_ctx)721722 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.726727 .. versionadded:: 0.11728 """729 rv = {"app": self, "g": g}730 for processor in self.shell_context_processors:731 rv.update(processor())732 return rv733734 @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.740741 **Do not enable debug mode when deploying in production.**742743 Default: ``False``744 """745 return self.config["DEBUG"]746747 @debug.setter748 def debug(self, value: bool) -> None:749 self.config["DEBUG"] = value750751 if self.config["TEMPLATES_AUTO_RELOAD"] is None:752 self.jinja_env.auto_reload = value753754 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.763764 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.767768 If the :attr:`debug` flag is set the server will automatically reload769 for code changes and show a debugger in case an exception happened.770771 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.775776 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.779780 .. admonition:: Keep in Mind781782 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.789790 :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.804805 .. versionchanged:: 1.0806 If installed, python-dotenv will be used to load environment807 variables from :file:`.env` and :file:`.flaskenv` files.808809 The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.810811 Threaded mode is enabled by default.812813 .. 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 )828829 return830831 if get_load_dotenv(load_dotenv):832 cli.load_dotenv()833834 # if set, env var overrides existing value835 if "FLASK_DEBUG" in os.environ:836 self.debug = get_debug_flag()837838 # debug passed to method overrides all other sources839 if debug is not None:840 self.debug = bool(debug)841842 server_name = self.config.get("SERVER_NAME")843 sn_host = sn_port = None844845 if server_name:846 sn_host, _, sn_port = server_name.partition(":")847848 if not host:849 if sn_host:850 host = sn_host851 else:852 host = "127.0.0.1"853854 if port or port == 0:855 port = int(port)856 elif sn_port:857 port = int(sn_port)858 else:859 port = 5000860861 options.setdefault("use_reloader", self.debug)862 options.setdefault("use_debugger", self.debug)863 options.setdefault("threaded", True)864865 cli.show_server_banner(self.debug, self.name)866867 from werkzeug.serving import run_simple868869 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 = False876877 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`.880881 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::888889 app.testing = True890 client = app.test_client()891892 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::895896 with app.test_client() as c:897 rv = c.get('/?vodka=42')898 assert request.args['vodka'] == '42'899900 Additionally, you may pass optional keyword arguments that will then901 be passed to the application's :attr:`test_client_class` constructor.902 For example::903904 from flask.testing import FlaskClient905906 class CustomClient(FlaskClient):907 def __init__(self, *args, **kwargs):908 self._authentication = kwargs.pop("authentication")909 super(CustomClient,self).__init__( *args, **kwargs)910911 app.test_client_class = CustomClient912 client = app.test_client(authentication='Basic ....')913914 See :class:`~flask.testing.FlaskClient` for more information.915916 .. versionchanged:: 0.4917 added support for ``with`` block usage for the client.918919 .. 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.923924 .. 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 )934935 def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner:936 """Create a CLI runner for testing CLI commands.937 See :ref:`testing-cli`.938939 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.942943 .. versionadded:: 1.0944 """945 cls = self.test_cli_runner_class946947 if cls is None:948 from .testing import FlaskCliRunner as cls949950 return cls(self, **kwargs) # type: ignore951952 @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.957958 Calls the blueprint's :meth:`~flask.Blueprint.register` method after959 recording the blueprint in the application's :attr:`blueprints`.960961 :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.969970 .. 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``.975976 .. versionadded:: 0.7977 """978 blueprint.register(self, options)979980 def iter_blueprints(self) -> t.ValuesView[Blueprint]:981 """Iterates over all blueprints by the order they were registered.982983 .. versionadded:: 0.11984 """985 return self.blueprints.values()986987 @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)10001001 # 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}10121013 # Methods that should always be added1014 required_methods = set(getattr(view_func, "required_methods", ()))10151016 # 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 )10221023 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 = False10291030 # Add the required methods now.1031 methods |= required_methods10321033 rule = self.url_rule_class(rule, methods=methods, **options)1034 rule.provide_automatic_options = provide_automatic_options # type: ignore10351036 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_func10451046 @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::10531054 @app.template_filter()1055 def reverse(s):1056 return s[::-1]10571058 :param name: the optional name of the filter, otherwise the1059 function name will be used.1060 """10611062 def decorator(f: T_template_filter) -> T_template_filter:1063 self.add_template_filter(f, name=name)1064 return f10651066 return decorator10671068 @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.10741075 :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__] = f10791080 @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::10871088 @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 True10961097 .. versionadded:: 0.1010981099 :param name: the optional name of the test, otherwise the1100 function name will be used.1101 """11021103 def decorator(f: T_template_test) -> T_template_test:1104 self.add_template_test(f, name=name)1105 return f11061107 return decorator11081109 @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.11151116 .. versionadded:: 0.1011171118 :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__] = f11221123 @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::11301131 @app.template_global()1132 def double(n):1133 return 2 * n11341135 .. versionadded:: 0.1011361137 :param name: the optional name of the global function, otherwise the1138 function name will be used.1139 """11401141 def decorator(f: T_template_global) -> T_template_global:1142 self.add_template_global(f, name=name)1143 return f11441145 return decorator11461147 @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.11531154 .. versionadded:: 0.1011551156 :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__] = f11601161 @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.11671168 .. code-block:: python11691170 with app.app_context():1171 ...11721173 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.11781179 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.11831184 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.11871188 The return values of teardown functions are ignored.11891190 .. versionadded:: 0.91191 """1192 self.teardown_appcontext_funcs.append(f)1193 return f11941195 @setupmethod1196 def shell_context_processor(1197 self, f: T_shell_context_processor1198 ) -> T_shell_context_processor:1199 """Registers a shell context processor function.12001201 .. versionadded:: 0.111202 """1203 self.shell_context_processors.append(f)1204 return f12051206 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)12141215 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]12181219 if not handler_map:1220 continue12211222 for cls in exc_class.__mro__:1223 handler = handler_map.get(cls)12241225 if handler is not None:1226 return handler1227 return None12281229 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.12351236 .. versionchanged:: 1.0.31237 ``RoutingException``, used internally for actions such as1238 slash redirects during routing, is not passed to error1239 handlers.12401241 .. 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``.12451246 .. 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 e12521253 # 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 e12581259 handler = self._find_error_handler(e)1260 if handler is None:1261 return e1262 return self.ensure_sync(handler)(e)12631264 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``.12691270 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.12751276 .. versionchanged:: 1.01277 Bad request errors are not trapped by default in debug mode.12781279 .. versionadded:: 0.81280 """1281 if self.config["TRAP_HTTP_EXCEPTIONS"]:1282 return True12831284 trap_bad_request = self.config["TRAP_BAD_REQUEST_ERRORS"]12851286 # 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 True12931294 if trap_bad_request:1295 return isinstance(e, BadRequest)12961297 return False12981299 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.13081309 .. 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.13131314 .. versionadded:: 0.71315 """1316 if isinstance(e, BadRequestKeyError) and (1317 self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]1318 ):1319 e.show_exception = True13201321 if isinstance(e, HTTPException) and not self.trap_http_exception(e):1322 return self.handle_http_exception(e)13231324 handler = self._find_error_handler(e)13251326 if handler is None:1327 raise13281329 return self.ensure_sync(handler)(e)13301331 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``.13351336 Always sends the :data:`got_request_exception` signal.13371338 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.13421343 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``.13471348 .. versionchanged:: 1.1.01349 Always passes the ``InternalServerError`` instance to the1350 handler, setting ``original_exception`` to the unhandled1351 error.13521353 .. versionchanged:: 1.1.01354 ``after_request`` functions and other finalization is done1355 even for the default 500 response when there is no handler.13561357 .. 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"]13621363 if propagate is None:1364 propagate = self.testing or self.debug13651366 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 raise13711372 raise e13731374 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)13781379 if handler is not None:1380 server_error = self.ensure_sync(handler)(server_error)13811382 return self.finalize_request(server_error, from_error_handler=True)13831384 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`.13921393 .. versionadded:: 0.81394 """1395 self.logger.error(1396 f"Exception on {request.path} [{request.method}]", exc_info=exc_info1397 )13981399 def raise_routing_exception(self, request: Request) -> t.NoReturn:1400 """Intercept routing exceptions and possibly do something else.14011402 In debug mode, intercept a routing redirect and replace it with1403 an error if the body will be discarded.14041405 With modern Werkzeug this shouldn't occur, since it now uses a1406 308 status which tells the browser to resend the method and1407 body.14081409 .. versionchanged:: 2.11410 Don't intercept 307 and 308 redirects.14111412 :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: ignore14221423 from .debughelpers import FormDataRoutingRedirect14241425 raise FormDataRoutingRedirect(request)14261427 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`.14321433 .. 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)14511452 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.14561457 .. versionadded:: 0.71458 """1459 self._got_first_request = True14601461 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)14691470 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.14791480 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.14841485 :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 response15001501 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.15051506 .. 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 rv15131514 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.15191520 .. versionadded:: 0.101521 """1522 return False15231524 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.15281529 Override this method to change how the app runs async views.15301531 .. versionadded:: 2.01532 """1533 if iscoroutinefunction(func):1534 return self.async_to_sync(func)15351536 return func15371538 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.15421543 .. code-block:: python15441545 result = app.async_to_sync(func)(*args, **kwargs)15461547 Override this method to change how the app converts async code1548 to be synchronously callable.15491550 .. 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 None15581559 return asgiref_async_to_sync(func)15601561 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.15721573 This is called by :func:`flask.url_for`, and can be called1574 directly as well.15751576 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.15811582 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.15891590 Functions can be decorated with :meth:`url_defaults` to modify1591 keyword arguments before the URL is built.15921593 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.15971598 :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``.16131614 .. versionadded:: 2.21615 Moved from ``flask.url_for``, which calls this method.1616 """1617 req_ctx = _cv_request.get(None)16181619 if req_ctx is not None:1620 url_adapter = req_ctx.url_adapter1621 blueprint_name = req_ctx.request.blueprint16221623 # 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:]16301631 # 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)16371638 # 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)16451646 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 )16531654 # When outside a request, generate a URL with scheme and1655 # domain by default.1656 if _external is None:1657 _external = True16581659 # 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.")16631664 self.inject_url_defaults(endpoint, values)16651666 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)16791680 if _anchor is not None:1681 _anchor = _url_quote(_anchor, safe="%!#$&'()*+,/:;=?@")1682 rv = f"{rv}#{_anchor}"16831684 return rv16851686 def redirect(self, location: str, code: int = 302) -> BaseResponse:1687 """Create a redirect response object.16881689 This is called by :func:`flask.redirect`, and can be called1690 directly as well.16911692 :param location: The URL to redirect to.1693 :param code: The status code for the redirect.16941695 .. versionadded:: 2.21696 Moved from ``flask.redirect``, which calls this method.1697 """1698 return _wz_redirect(location, code=code, Response=self.response_class)16991700 def make_response(self, rv: ft.ResponseReturnValue) -> Response:1701 """Convert the return value from a view function to an instance of1702 :attr:`response_class`.17031704 :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``:17081709 ``str``1710 A response object is created with the string encoded to UTF-81711 as the body.17121713 ``bytes``1714 A response object is created with the bytes as the body.17151716 ``dict``1717 A dictionary that will be jsonify'd before being returned.17181719 ``list``1720 A list that will be jsonify'd before being returned.17211722 ``generator`` or ``iterator``1723 A generator that returns ``str`` or ``bytes`` to be1724 streamed as the response.17251726 ``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.17341735 :attr:`response_class`1736 The object is returned unchanged.17371738 other :class:`~werkzeug.wrappers.Response` class1739 The object is coerced to :attr:`response_class`.17401741 :func:`callable`1742 The function is called as a WSGI application. The result is1743 used to create a response object.17441745 .. versionchanged:: 2.21746 A generator will be converted to a streaming response.1747 A list will be converted to a JSON response.17481749 .. versionchanged:: 1.11750 A dict will be converted to a JSON response.17511752 .. versionchanged:: 0.91753 Previously a tuple was interpreted as the arguments for the1754 response object.1755 """17561757 status = headers = None17581759 # unpack tuple returns1760 if isinstance(rv, tuple):1761 len_rv = len(rv)17621763 # 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 )17791780 # 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 )17871788 # 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 )18251826 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 = status18331834 # extend existing headers with provided headers1835 if headers:1836 rv.headers.update(headers) # type: ignore[arg-type]18371838 return rv18391840 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.18441845 .. versionadded:: 0.618461847 .. versionchanged:: 0.91848 This can now also be called without a request object when the1849 URL adapter is created for the application context.18501851 .. 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 = None18631864 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 )18771878 return None18791880 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.18841885 .. versionadded:: 0.71886 """1887 names: t.Iterable[str | None] = (None,)18881889 # 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 )18951896 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)19001901 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.19081909 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``.19131914 :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 rv19271928 # Re-raise if called with an active exception, otherwise raise1929 # the passed in exception.1930 if error is sys.exc_info()[1]:1931 raise19321933 raise error19341935 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.19401941 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))19461947 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)19511952 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)()19561957 if rv is not None:1958 return rv19591960 return None19611962 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.19661967 .. versionchanged:: 0.51968 As of Flask 0.5 the functions registered for after request1969 execution are called in reverse order of registration.19701971 :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]19761977 for func in ctx._after_request_functions:1978 response = self.ensure_sync(func)(response)19791980 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)19841985 if not self.session_interface.is_null_session(ctx.session):1986 self.session_interface.save_session(self, ctx.session, response)19871988 return response19891990 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.19951996 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.20002001 This is called by2002 :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`,2003 which may be delayed during testing to maintain access to2004 resources.20052006 :param exc: An unhandled exception raised while dispatching the2007 request. Detected from the current exception information if2008 not passed. Passed to each teardown function.20092010 .. versionchanged:: 0.92011 Added the ``exc`` argument.2012 """2013 if exc is _sentinel:2014 exc = sys.exc_info()[1]20152016 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)20202021 request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)20222023 def do_teardown_appcontext(2024 self, exc: BaseException | None = _sentinel # type: ignore2025 ) -> None:2026 """Called right before the application context is popped.20272028 When handling a request, the application context is popped2029 after the request context. See :meth:`do_teardown_request`.20302031 This calls all functions decorated with2032 :meth:`teardown_appcontext`. Then the2033 :data:`appcontext_tearing_down` signal is sent.20342035 This is called by2036 :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.20372038 .. versionadded:: 0.92039 """2040 if exc is _sentinel:2041 exc = sys.exc_info()[1]20422043 for func in reversed(self.teardown_appcontext_funcs):2044 self.ensure_sync(func)(exc)20452046 appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)20472048 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.20522053 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.20572058 ::20592060 with app.app_context():2061 init_db()20622063 See :doc:`/appcontext`.20642065 .. versionadded:: 0.92066 """2067 return AppContext(self)20682069 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.20732074 See :doc:`/reqcontext`.20752076 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.20802081 :param environ: a WSGI environment2082 """2083 return RequestContext(self, environ)20842085 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.20902091 See :doc:`/reqcontext`.20922093 Use a ``with`` block to push the context, which will make2094 :data:`request` point at the request for the created2095 environment. ::20962097 with app.test_request_context(...):2098 generate_report()20992100 When using the shell, it may be easier to push and pop the2101 context manually to avoid indentation. ::21022103 ctx = app.test_request_context(...)2104 ctx.push()2105 ...2106 ctx.pop()21072108 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.21122113 :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 EnvironBuilder21332134 builder = EnvironBuilder(self, *args, **kwargs)21352136 try:2137 return self.request_context(builder.get_environ())2138 finally:2139 builder.close()21402141 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::21452146 app = MyMiddleware(app)21472148 It's a better idea to do this instead::21492150 app.wsgi_app = MyMiddleware(app.wsgi_app)21512152 Then you still have the original application object around and2153 can continue to call methods on it.21542155 .. 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`.21602161 :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())21832184 if error is not None and self.should_ignore_error(error):2185 error = None21862187 ctx.pop(error)21882189 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
1from __future__ import annotations23import os4import typing as t5from collections import defaultdict6from functools import update_wrapper78from . import typing as ft9from .scaffold import _endpoint_from_view_func10from .scaffold import _sentinel11from .scaffold import Scaffold12from .scaffold import setupmethod1314if t.TYPE_CHECKING: # pragma: no cover15 from .app import Flask1617DeferredSetupFunction = t.Callable[["BlueprintSetupState"], t.Callable]18T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable)19T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable)20T_error_handler = t.TypeVar("T_error_handler", bound=ft.ErrorHandlerCallable)21T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)22T_template_context_processor = t.TypeVar(23 "T_template_context_processor", bound=ft.TemplateContextProcessorCallable24)25T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable)26T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable)27T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable)28T_url_defaults = t.TypeVar("T_url_defaults", bound=ft.URLDefaultCallable)29T_url_value_preprocessor = t.TypeVar(30 "T_url_value_preprocessor", bound=ft.URLValuePreprocessorCallable31)323334class 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 """4041 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 = app5051 #: a reference to the blueprint that created this setup state.52 self.blueprint = blueprint5354 #: a dictionary with all options that were passed to the55 #: :meth:`~flask.Flask.register_blueprint` method.56 self.options = options5758 #: 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_registration6364 subdomain = self.options.get("subdomain")65 if subdomain is None:66 subdomain = self.blueprint.subdomain6768 #: The subdomain that the blueprint should be active for, ``None``69 #: otherwise.70 self.subdomain = subdomain7172 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_prefix7879 self.name = self.options.get("name", blueprint.name)80 self.name_prefix = self.options.get("name_prefix", "")8182 #: 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", ()))8687 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"))109110 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 )117118119class Blueprint(Scaffold):120 """Represents a blueprint, a collection of routes and other121 app-related functions that can be registered on a real application122 later.123124 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.128129 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.132133 See :doc:`/blueprints` for more information.134135 :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.163164 .. 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.168169 .. versionadded:: 0.7170 """171172 _got_registered_once = False173174 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 )194195 if not name:196 raise ValueError("'name' may not be empty.")197198 if "." in name:199 raise ValueError("'name' may not contain a dot '.' character.")200201 self.name = name202 self.url_prefix = url_prefix203 self.subdomain = subdomain204 self.deferred_functions: list[DeferredSetupFunction] = []205206 if url_defaults is None:207 url_defaults = {}208209 self.url_values_defaults = url_defaults210 self.cli_group = cli_group211 self._blueprints: list[tuple[Blueprint, dict]] = []212213 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 )222223 @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)231232 @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 """239240 def wrapper(state: BlueprintSetupState) -> None:241 if state.first_registration:242 func(state)243244 self.record(update_wrapper(wrapper, func))245246 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)254255 @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.260261 .. 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``.266267 .. versionadded:: 2.0268 """269 if blueprint is self:270 raise ValueError("Cannot register a blueprint on itself")271 self._blueprints.append((blueprint, options))272273 def register(self, app: 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.278279 :param app: The application this blueprint is being registered280 with.281 :param options: Keyword arguments forwarded from282 :meth:`~Flask.register_blueprint`.283284 .. versionchanged:: 2.3285 Nested blueprints now correctly apply subdomains.286287 .. versionchanged:: 2.1288 Registering the same blueprint with the same name multiple289 times is an error.290291 .. 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.295296 .. 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(".")305306 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 ""309310 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 )315316 first_bp_registration = not any(bp is self for bp in app.blueprints.values())317 first_name_registration = name not in app.blueprints318319 app.blueprints[name] = self320 self._got_registered_once = True321 state = self.make_setup_state(app, options, first_bp_registration)322323 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 )329330 # Merge blueprint data into parent.331 if first_bp_registration or first_name_registration:332333 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)337338 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] = value350351 for endpoint, func in self.view_functions.items():352 app.view_functions[endpoint] = func353354 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)363364 for deferred in self.deferred_functions:365 deferred(state)366367 cli_resolved_group = options.get("cli_group", self.cli_group)368369 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)378379 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")383384 if bp_subdomain is None:385 bp_subdomain = blueprint.subdomain386387 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.subdomain393394 if bp_url_prefix is None:395 bp_url_prefix = blueprint.url_prefix396397 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_prefix405406 bp_options["name_prefix"] = name407 blueprint.register(app, bp_options)408409 @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.420421 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.")426427 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.")429430 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 )439440 @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`.446447 :param name: the optional name of the filter, otherwise the448 function name will be used.449 """450451 def decorator(f: T_template_filter) -> T_template_filter:452 self.add_app_template_filter(f, name=name)453 return f454455 return decorator456457 @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`.464465 :param name: the optional name of the filter, otherwise the466 function name will be used.467 """468469 def register_template(state: BlueprintSetupState) -> None:470 state.app.jinja_env.filters[name or f.__name__] = f471472 self.record_once(register_template)473474 @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`.480481 .. versionadded:: 0.10482483 :param name: the optional name of the test, otherwise the484 function name will be used.485 """486487 def decorator(f: T_template_test) -> T_template_test:488 self.add_app_template_test(f, name=name)489 return f490491 return decorator492493 @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`.500501 .. versionadded:: 0.10502503 :param name: the optional name of the test, otherwise the504 function name will be used.505 """506507 def register_template(state: BlueprintSetupState) -> None:508 state.app.jinja_env.tests[name or f.__name__] = f509510 self.record_once(register_template)511512 @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`.518519 .. versionadded:: 0.10520521 :param name: the optional name of the global, otherwise the522 function name will be used.523 """524525 def decorator(f: T_template_global) -> T_template_global:526 self.add_app_template_global(f, name=name)527 return f528529 return decorator530531 @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`.538539 .. versionadded:: 0.10540541 :param name: the optional name of the global, otherwise the542 function name will be used.543 """544545 def register_template(state: BlueprintSetupState) -> None:546 state.app.jinja_env.globals[name or f.__name__] = f547548 self.record_once(register_template)549550 @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 f559560 @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 f569570 @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 f579580 @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 f591592 @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 """599600 def decorator(f: T_error_handler) -> T_error_handler:601 self.record_once(lambda s: s.app.errorhandler(code)(f))602 return f603604 return decorator605606 @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 f617618 @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 f
added:src/flask/sansio/scaffold.py+873 added
1from __future__ import annotations23import importlib.util4import os5import pathlib6import sys7import typing as t8from collections import defaultdict9from datetime import timedelta10from functools import update_wrapper1112from jinja2 import FileSystemLoader13from werkzeug.exceptions import default_exceptions14from werkzeug.exceptions import HTTPException15from werkzeug.utils import cached_property1617from . import typing as ft18from .cli import AppGroup19from .globals import current_app20from .helpers import get_root_path21from .helpers import send_from_directory22from .templating import _default_template_ctx_processor2324if t.TYPE_CHECKING: # pragma: no cover25 from .wrappers import Response2627# a singleton sentinel value for parameter defaults28_sentinel = object()2930F = t.TypeVar("F", bound=t.Callable[..., t.Any])31T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable)32T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable)33T_error_handler = t.TypeVar("T_error_handler", bound=ft.ErrorHandlerCallable)34T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)35T_template_context_processor = t.TypeVar(36 "T_template_context_processor", bound=ft.TemplateContextProcessorCallable37)38T_url_defaults = t.TypeVar("T_url_defaults", bound=ft.URLDefaultCallable)39T_url_value_preprocessor = t.TypeVar(40 "T_url_value_preprocessor", bound=ft.URLValuePreprocessorCallable41)42T_route = t.TypeVar("T_route", bound=ft.RouteCallable)434445def setupmethod(f: F) -> F:46 f_name = f.__name__4748 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)5152 return t.cast(F, update_wrapper(wrapper_func, f))535455class Scaffold:56 """Common behavior shared between :class:`~flask.Flask` and57 :class:`~flask.blueprints.Blueprint`.5859 :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``.6970 .. versionadded:: 2.071 """7273 name: str74 _static_folder: str | None = None75 _static_url_path: str | None = None7677 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_name8889 self.static_folder = static_folder # type: ignore90 self.static_url_path = static_url_path9192 #: 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_folder9697 if root_path is None:98 root_path = get_root_path(self.import_name)99100 #: Absolute path to the package on the filesystem. Used to look101 #: up resources contained in the package.102 self.root_path = root_path103104 #: 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()109110 #: 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] = {}117118 #: 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))135136 #: 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)149150 #: 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)163164 #: 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)178179 #: 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]})193194 #: 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)209210 #: 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)224225 def __repr__(self) -> str:226 return f"<{type(self).__name__} {self.name!r}>"227228 def _check_setup_finished(self, f_name: str) -> None:229 raise NotImplementedError230231 @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 None240241 @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"\/")245246 self._static_folder = value247248 @property249 def has_static_folder(self) -> bool:250 """``True`` if :attr:`static_folder` is set.251252 .. versionadded:: 0.5253 """254 return self.static_folder is not None255256 @property257 def static_url_path(self) -> str | None:258 """The URL prefix that the static route will be accessible from.259260 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_path265266 if self.static_folder is not None:267 basename = os.path.basename(self.static_folder)268 return f"/{basename}".rstrip("/")269270 return None271272 @static_url_path.setter273 def static_url_path(self, value: str | None) -> None:274 if value is not None:275 value = value.rstrip("/")276277 self._static_url_path = value278279 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.282283 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.287288 .. versionchanged:: 2.0289 The default configuration is ``None`` instead of 12 hours.290291 .. versionadded:: 0.9292 """293 value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]294295 if value is None:296 return None297298 if isinstance(value, timedelta):299 return int(value.total_seconds())300301 return value302303 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.308309 .. versionadded:: 0.5310 """311 if not self.has_static_folder:312 raise RuntimeError("'static_folder' must be set to serve static_files.")313314 # 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 )320321 @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.326327 .. 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 None333334 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.337338 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:341342 .. code-block:: python343344 with app.open_resource("schema.sql") as f:345 conn.executescript(f.read())346347 :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.")354355 return open(os.path.join(self.root_path, resource), mode)356357 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.")365366 return self.route(rule, methods=[method], **options)367368 @setupmethod369 def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:370 """Shortcut for :meth:`route` with ``methods=["GET"]``.371372 .. versionadded:: 2.0373 """374 return self._method_route("GET", rule, options)375376 @setupmethod377 def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:378 """Shortcut for :meth:`route` with ``methods=["POST"]``.379380 .. versionadded:: 2.0381 """382 return self._method_route("POST", rule, options)383384 @setupmethod385 def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:386 """Shortcut for :meth:`route` with ``methods=["PUT"]``.387388 .. versionadded:: 2.0389 """390 return self._method_route("PUT", rule, options)391392 @setupmethod393 def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:394 """Shortcut for :meth:`route` with ``methods=["DELETE"]``.395396 .. versionadded:: 2.0397 """398 return self._method_route("DELETE", rule, options)399400 @setupmethod401 def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:402 """Shortcut for :meth:`route` with ``methods=["PATCH"]``.403404 .. versionadded:: 2.0405 """406 return self._method_route("PATCH", rule, options)407408 @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.413414 .. code-block:: python415416 @app.route("/")417 def index():418 return "Hello, World!"419420 See :ref:`url-route-registrations`.421422 The endpoint name for the route defaults to the name of the view423 function if the ``endpoint`` parameter isn't passed.424425 The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and426 ``OPTIONS`` are added automatically.427428 :param rule: The URL rule string.429 :param options: Extra options passed to the430 :class:`~werkzeug.routing.Rule` object.431 """432433 def decorator(f: T_route) -> T_route:434 endpoint = options.pop("endpoint", None)435 self.add_url_rule(rule, endpoint, f, **options)436 return f437438 return decorator439440 @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:452453 .. code-block:: python454455 @app.route("/")456 def index():457 ...458459 .. code-block:: python460461 def index():462 ...463464 app.add_url_rule("/", view_func=index)465466 See :ref:`url-route-registrations`.467468 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.472473 The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` is474 always added automatically, and ``OPTIONS`` is added475 automatically by default.476477 ``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.481482 .. code-block:: python483484 app.add_url_rule("/", endpoint="index")485486 @app.endpoint("index")487 def index():488 ...489490 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.494495 :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 NotImplementedError507508 @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`.513514 .. code-block:: python515516 app.add_url_rule("/ex", endpoint="example")517518 @app.endpoint("example")519 def example():520 ...521522 :param endpoint: The endpoint name to associate with the view523 function.524 """525526 def decorator(f: F) -> F:527 self.view_functions[endpoint] = f528 return f529530 return decorator531532 @setupmethod533 def before_request(self, f: T_before_request) -> T_before_request:534 """Register a function to run before each request.535536 For example, this can be used to open a database connection, or537 to load the logged in user from the session.538539 .. code-block:: python540541 @app.before_request542 def load_user():543 if "user_id" in session:544 g.user = db.session.get(session["user_id"])545546 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.550551 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 f558559 @setupmethod560 def after_request(self, f: T_after_request) -> T_after_request:561 """Register a function to run after each request to this object.562563 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.566567 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.571572 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 f579580 @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.585586 .. code-block:: python587588 with app.test_request_context():589 ...590591 When the ``with`` block exits (or ``ctx.pop()`` is called), the592 teardown functions are called just before the request context is593 made inactive.594595 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.599600 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.603604 The return values of teardown functions are ignored.605606 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 f613614 @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.622623 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 f630631 @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.639640 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.644645 The function is passed the endpoint name and values dict. The return646 value is ignored.647648 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 f655656 @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.661662 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 f669670 @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.675676 A decorator that is used to register a function given an677 error code. Example::678679 @app.errorhandler(404)680 def page_not_found(error):681 return 'This page does not exist', 404682683 You can also register handlers for arbitrary exceptions::684685 @app.errorhandler(DatabaseError)686 def special_exception_handler(error):687 return 'Database connection failed', 500688689 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`.693694 .. versionadded:: 0.7695 Use :meth:`register_error_handler` instead of modifying696 :attr:`error_handler_spec` directly, for application wide error697 handlers.698699 .. 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.703704 :param code_or_exception: the code as integer for the handler, or705 an arbitrary exception706 """707708 def decorator(f: T_error_handler) -> T_error_handler:709 self.register_error_handler(code_or_exception, f)710 return f711712 return decorator713714 @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.723724 .. 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] = f728729 @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.736737 :param exc_class_or_code: Any exception class, or an HTTP status738 code as an integer.739 """740 exc_class: type[Exception]741742 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_code753754 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 )760761 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 )767768 if issubclass(exc_class, HTTPException):769 return exc_class, exc_class.code770 else:771 return exc_class, None772773774def _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__780781782def _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 False789790791def _find_package_path(import_name):792 """Find the path that contains the package or module."""793 root_mod_name, _, _ = import_name.partition(".")794795 try:796 root_spec = importlib.util.find_spec(root_mod_name)797798 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()807808 if root_spec.origin in {"namespace", None}:809 # namespace package810 package_spec = importlib.util.find_spec(import_name)811812 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]825826 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)833834835def find_package(import_name: str):836 """Find the prefix that a package is installed under, and the path837 that it would be imported from.838839 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.843844 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)850851 # installed to the system852 if _path_is_relative_to(pathlib.PurePath(package_path), py_prefix):853 return py_prefix, package_path854855 site_parent, site_folder = os.path.split(package_path)856857 # installed to a virtualenv858 if site_folder.lower() == "site-packages":859 parent, folder = os.path.split(site_parent)860861 # Windows (prefix/lib/site-packages)862 if folder.lower() == "lib":863 return parent, package_path864865 # Unix (prefix/lib/pythonX.Y/site-packages)866 if os.path.basename(parent).lower() == "lib":867 return os.path.dirname(parent), package_path868869 # something else (prefix/site-packages)870 return site_parent, package_path871872 # not installed873 return None, package_path
deleted:src/flask/app.py-2194 removed
1from __future__ import annotations23import logging4import os5import sys6import typing as t7import weakref8from collections.abc import Iterator as _abc_Iterator9from datetime import timedelta10from inspect import iscoroutinefunction11from itertools import chain12from types import TracebackType13from urllib.parse import quote as _url_quote1415import click16from werkzeug.datastructures import Headers17from werkzeug.datastructures import ImmutableDict18from werkzeug.exceptions import Aborter19from werkzeug.exceptions import BadRequest20from werkzeug.exceptions import BadRequestKeyError21from werkzeug.exceptions import HTTPException22from werkzeug.exceptions import InternalServerError23from werkzeug.routing import BuildError24from werkzeug.routing import Map25from werkzeug.routing import MapAdapter26from werkzeug.routing import RequestRedirect27from werkzeug.routing import RoutingException28from werkzeug.routing import Rule29from werkzeug.serving import is_running_from_reloader30from werkzeug.utils import cached_property31from werkzeug.utils import redirect as _wz_redirect32from werkzeug.wrappers import Response as BaseResponse3334from . import cli35from . import typing as ft36from .config import Config37from .config import ConfigAttribute38from .ctx import _AppCtxGlobals39from .ctx import AppContext40from .ctx import RequestContext41from .globals import _cv_app42from .globals import _cv_request43from .globals import g44from .globals import request45from .globals import request_ctx46from .globals import session47from .helpers import _split_blueprint_path48from .helpers import get_debug_flag49from .helpers import get_flashed_messages50from .helpers import get_load_dotenv51from .json.provider import DefaultJSONProvider52from .json.provider import JSONProvider53from .logging import create_logger54from .scaffold import _endpoint_from_view_func55from .scaffold import _sentinel56from .scaffold import find_package57from .scaffold import Scaffold58from .scaffold import setupmethod59from .sessions import SecureCookieSessionInterface60from .sessions import SessionInterface61from .signals import appcontext_tearing_down62from .signals import got_request_exception63from .signals import request_finished64from .signals import request_started65from .signals import request_tearing_down66from .templating import DispatchingJinjaLoader67from .templating import Environment68from .wrappers import Request69from .wrappers import Response7071if t.TYPE_CHECKING: # pragma: no cover72 from .blueprints import Blueprint73 from .testing import FlaskClient74 from .testing import FlaskCliRunner7576T_shell_context_processor = t.TypeVar(77 "T_shell_context_processor", bound=ft.ShellContextProcessorCallable78)79T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)80T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable)81T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable)82T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable)838485def _make_timedelta(value: timedelta | int | None) -> timedelta | None:86 if value is None or isinstance(value, timedelta):87 return value8889 return timedelta(seconds=value)909192class 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.9798 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).102103 For more information about resource loading, see :func:`open_resource`.104105 Usually you create a :class:`Flask` instance in your main module or106 in the :file:`__init__.py` file of your package like this::107108 from flask import Flask109 app = Flask(__name__)110111 .. admonition:: About the First Parameter112113 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.117118 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.122123 For example if your application is defined in :file:`yourapplication/app.py`124 you should create it with one of the two versions below::125126 app = Flask('yourapplication')127 app = Flask(__name__.split('.')[0])128129 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`)138139 .. versionadded:: 0.7140 The `static_url_path`, `static_folder`, and `template_folder`141 parameters were added.142143 .. versionadded:: 0.8144 The `instance_path` and `instance_relative_config` parameters were145 added.146147 .. versionadded:: 0.11148 The `root_path` parameter was added.149150 .. versionadded:: 1.0151 The ``host_matching`` and ``static_host`` parameters were added.152153 .. 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.157158 :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 """188189 #: The class that is used for request objects. See :class:`~flask.Request`190 #: for more information.191 request_class = Request192193 #: The class that is used for response objects. See194 #: :class:`~flask.Response` for more information.195 response_class = Response196197 #: 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 = Aborter206207 #: The class that is used for the Jinja environment.208 #:209 #: .. versionadded:: 0.11210 jinja_environment = Environment211212 #: 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 = _AppCtxGlobals227228 #: 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 = Config238239 #: 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")250251 #: 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")258259 #: 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 )269270 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.274275 The default, :class:`~flask.json.provider.DefaultJSONProvider`, uses276 Python's built-in :mod:`json` library. A different provider can use277 a different JSON library.278279 .. versionadded:: 2.2280 """281282 #: 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 = {}292293 #: 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 )321322 #: 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 = Rule327328 #: 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 = Map333334 #: 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 = None339340 #: 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 = None347348 #: 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()353354 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 )374375 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 )382383 #: Holds the path to the instance folder.384 #:385 #: .. versionadded:: 0.8386 self.instance_path = instance_path387388 #: 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)392393 #: 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()400401 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.405406 An instance of :attr:`json_provider_class`. Can be customized by407 changing that attribute on a subclass, or by assigning to this408 attribute afterwards.409410 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.413414 .. versionadded:: 2.2415 """416417 #: 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 ] = []428429 #: 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] = []436437 #: 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] = []442443 #: 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] = {}450451 #: 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 = {}461462 #: 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()478479 self.url_map.host_matching = host_matching480 self.subdomain_matching = subdomain_matching481482 # tracks internally if the application already handled at least one483 # request.484 self._got_first_request = False485486 # 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 )504505 # 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.name508509 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 )520521 @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.528529 .. 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_name537538 @cached_property539 def logger(self) -> logging.Logger:540 """A standard Python :class:`~logging.Logger` for the app, with541 the same name as :attr:`name`.542543 In debug mode, the logger's :attr:`~logging.Logger.level` will544 be set to :data:`~logging.DEBUG`.545546 If there are no handlers configured, a default handler will be547 added. See :doc:`/logging` for more information.548549 .. versionchanged:: 1.1.0550 The logger takes the same name as :attr:`name` rather than551 hard-coding ``"flask.app"``.552553 .. 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.560561 .. versionadded:: 0.3562 """563 return create_logger(self)564565 @cached_property566 def jinja_env(self) -> Environment:567 """The Jinja environment used to load templates.568569 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()574575 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.581582 .. 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)590591 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.595596 By default, this creates an instance of :attr:`aborter_class`,597 which defaults to :class:`werkzeug.exceptions.Aborter`.598599 .. versionadded:: 2.2600 """601 return self.aborter_class()602603 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.608609 .. 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")615616 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.621622 :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)627628 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.633634 .. versionchanged:: 0.11635 ``Environment.auto_reload`` set in accordance with636 ``TEMPLATES_AUTO_RELOAD`` configuration option.637638 .. versionadded:: 0.5639 """640 options = dict(self.jinja_options)641642 if "autoescape" not in options:643 options["autoescape"] = self.select_jinja_autoescape644645 if "auto_reload" not in options:646 auto_reload = self.config["TEMPLATES_AUTO_RELOAD"]647648 if auto_reload is None:649 auto_reload = self.debug650651 options["auto_reload"] = auto_reload652653 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 rv667668 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.673674 The global loader dispatches between the loaders of the application675 and the individual blueprints.676677 .. versionadded:: 0.7678 """679 return DispatchingJinjaLoader(self)680681 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`.684685 .. versionchanged:: 2.2686 Autoescaping is now enabled by default for ``.svg`` files.687688 .. versionadded:: 0.5689 """690 if filename is None:691 return True692 return filename.endswith((".html", ".htm", ".xml", ".xhtml", ".svg"))693694 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.701702 :param context: the context as a dictionary that is updated in place703 to add extra variables.704 """705 names: t.Iterable[str | None] = (None,)706707 # A template may be rendered outside a request context.708 if request:709 names = chain(names, reversed(request.blueprints))710711 # The values passed to render_template take precedence. Keep a712 # copy to re-apply after all context functions.713 orig_ctx = context.copy()714715 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())719720 context.update(orig_ctx)721722 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.726727 .. versionadded:: 0.11728 """729 rv = {"app": self, "g": g}730 for processor in self.shell_context_processors:731 rv.update(processor())732 return rv733734 @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.740741 **Do not enable debug mode when deploying in production.**742743 Default: ``False``744 """745 return self.config["DEBUG"]746747 @debug.setter748 def debug(self, value: bool) -> None:749 self.config["DEBUG"] = value750751 if self.config["TEMPLATES_AUTO_RELOAD"] is None:752 self.jinja_env.auto_reload = value753754 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.763764 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.767768 If the :attr:`debug` flag is set the server will automatically reload769 for code changes and show a debugger in case an exception happened.770771 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.775776 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.779780 .. admonition:: Keep in Mind781782 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.789790 :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.804805 .. versionchanged:: 1.0806 If installed, python-dotenv will be used to load environment807 variables from :file:`.env` and :file:`.flaskenv` files.808809 The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.810811 Threaded mode is enabled by default.812813 .. 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 )828829 return830831 if get_load_dotenv(load_dotenv):832 cli.load_dotenv()833834 # if set, env var overrides existing value835 if "FLASK_DEBUG" in os.environ:836 self.debug = get_debug_flag()837838 # debug passed to method overrides all other sources839 if debug is not None:840 self.debug = bool(debug)841842 server_name = self.config.get("SERVER_NAME")843 sn_host = sn_port = None844845 if server_name:846 sn_host, _, sn_port = server_name.partition(":")847848 if not host:849 if sn_host:850 host = sn_host851 else:852 host = "127.0.0.1"853854 if port or port == 0:855 port = int(port)856 elif sn_port:857 port = int(sn_port)858 else:859 port = 5000860861 options.setdefault("use_reloader", self.debug)862 options.setdefault("use_debugger", self.debug)863 options.setdefault("threaded", True)864865 cli.show_server_banner(self.debug, self.name)866867 from werkzeug.serving import run_simple868869 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 = False876877 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`.880881 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::888889 app.testing = True890 client = app.test_client()891892 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::895896 with app.test_client() as c:897 rv = c.get('/?vodka=42')898 assert request.args['vodka'] == '42'899900 Additionally, you may pass optional keyword arguments that will then901 be passed to the application's :attr:`test_client_class` constructor.902 For example::903904 from flask.testing import FlaskClient905906 class CustomClient(FlaskClient):907 def __init__(self, *args, **kwargs):908 self._authentication = kwargs.pop("authentication")909 super(CustomClient,self).__init__( *args, **kwargs)910911 app.test_client_class = CustomClient912 client = app.test_client(authentication='Basic ....')913914 See :class:`~flask.testing.FlaskClient` for more information.915916 .. versionchanged:: 0.4917 added support for ``with`` block usage for the client.918919 .. 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.923924 .. 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 )934935 def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner:936 """Create a CLI runner for testing CLI commands.937 See :ref:`testing-cli`.938939 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.942943 .. versionadded:: 1.0944 """945 cls = self.test_cli_runner_class946947 if cls is None:948 from .testing import FlaskCliRunner as cls949950 return cls(self, **kwargs) # type: ignore951952 @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.957958 Calls the blueprint's :meth:`~flask.Blueprint.register` method after959 recording the blueprint in the application's :attr:`blueprints`.960961 :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.969970 .. 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``.975976 .. versionadded:: 0.7977 """978 blueprint.register(self, options)979980 def iter_blueprints(self) -> t.ValuesView[Blueprint]:981 """Iterates over all blueprints by the order they were registered.982983 .. versionadded:: 0.11984 """985 return self.blueprints.values()986987 @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)10001001 # 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}10121013 # Methods that should always be added1014 required_methods = set(getattr(view_func, "required_methods", ()))10151016 # 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 )10221023 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 = False10291030 # Add the required methods now.1031 methods |= required_methods10321033 rule = self.url_rule_class(rule, methods=methods, **options)1034 rule.provide_automatic_options = provide_automatic_options # type: ignore10351036 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_func10451046 @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::10531054 @app.template_filter()1055 def reverse(s):1056 return s[::-1]10571058 :param name: the optional name of the filter, otherwise the1059 function name will be used.1060 """10611062 def decorator(f: T_template_filter) -> T_template_filter:1063 self.add_template_filter(f, name=name)1064 return f10651066 return decorator10671068 @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.10741075 :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__] = f10791080 @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::10871088 @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 True10961097 .. versionadded:: 0.1010981099 :param name: the optional name of the test, otherwise the1100 function name will be used.1101 """11021103 def decorator(f: T_template_test) -> T_template_test:1104 self.add_template_test(f, name=name)1105 return f11061107 return decorator11081109 @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.11151116 .. versionadded:: 0.1011171118 :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__] = f11221123 @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::11301131 @app.template_global()1132 def double(n):1133 return 2 * n11341135 .. versionadded:: 0.1011361137 :param name: the optional name of the global function, otherwise the1138 function name will be used.1139 """11401141 def decorator(f: T_template_global) -> T_template_global:1142 self.add_template_global(f, name=name)1143 return f11441145 return decorator11461147 @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.11531154 .. versionadded:: 0.1011551156 :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__] = f11601161 @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.11671168 .. code-block:: python11691170 with app.app_context():1171 ...11721173 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.11781179 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.11831184 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.11871188 The return values of teardown functions are ignored.11891190 .. versionadded:: 0.91191 """1192 self.teardown_appcontext_funcs.append(f)1193 return f11941195 @setupmethod1196 def shell_context_processor(1197 self, f: T_shell_context_processor1198 ) -> T_shell_context_processor:1199 """Registers a shell context processor function.12001201 .. versionadded:: 0.111202 """1203 self.shell_context_processors.append(f)1204 return f12051206 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)12141215 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]12181219 if not handler_map:1220 continue12211222 for cls in exc_class.__mro__:1223 handler = handler_map.get(cls)12241225 if handler is not None:1226 return handler1227 return None12281229 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.12351236 .. versionchanged:: 1.0.31237 ``RoutingException``, used internally for actions such as1238 slash redirects during routing, is not passed to error1239 handlers.12401241 .. 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``.12451246 .. 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 e12521253 # 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 e12581259 handler = self._find_error_handler(e)1260 if handler is None:1261 return e1262 return self.ensure_sync(handler)(e)12631264 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``.12691270 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.12751276 .. versionchanged:: 1.01277 Bad request errors are not trapped by default in debug mode.12781279 .. versionadded:: 0.81280 """1281 if self.config["TRAP_HTTP_EXCEPTIONS"]:1282 return True12831284 trap_bad_request = self.config["TRAP_BAD_REQUEST_ERRORS"]12851286 # 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 True12931294 if trap_bad_request:1295 return isinstance(e, BadRequest)12961297 return False12981299 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.13081309 .. 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.13131314 .. versionadded:: 0.71315 """1316 if isinstance(e, BadRequestKeyError) and (1317 self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]1318 ):1319 e.show_exception = True13201321 if isinstance(e, HTTPException) and not self.trap_http_exception(e):1322 return self.handle_http_exception(e)13231324 handler = self._find_error_handler(e)13251326 if handler is None:1327 raise13281329 return self.ensure_sync(handler)(e)13301331 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``.13351336 Always sends the :data:`got_request_exception` signal.13371338 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.13421343 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``.13471348 .. versionchanged:: 1.1.01349 Always passes the ``InternalServerError`` instance to the1350 handler, setting ``original_exception`` to the unhandled1351 error.13521353 .. versionchanged:: 1.1.01354 ``after_request`` functions and other finalization is done1355 even for the default 500 response when there is no handler.13561357 .. 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"]13621363 if propagate is None:1364 propagate = self.testing or self.debug13651366 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 raise13711372 raise e13731374 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)13781379 if handler is not None:1380 server_error = self.ensure_sync(handler)(server_error)13811382 return self.finalize_request(server_error, from_error_handler=True)13831384 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`.13921393 .. versionadded:: 0.81394 """1395 self.logger.error(1396 f"Exception on {request.path} [{request.method}]", exc_info=exc_info1397 )13981399 def raise_routing_exception(self, request: Request) -> t.NoReturn:1400 """Intercept routing exceptions and possibly do something else.14011402 In debug mode, intercept a routing redirect and replace it with1403 an error if the body will be discarded.14041405 With modern Werkzeug this shouldn't occur, since it now uses a1406 308 status which tells the browser to resend the method and1407 body.14081409 .. versionchanged:: 2.11410 Don't intercept 307 and 308 redirects.14111412 :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: ignore14221423 from .debughelpers import FormDataRoutingRedirect14241425 raise FormDataRoutingRedirect(request)14261427 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`.14321433 .. 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)14511452 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.14561457 .. versionadded:: 0.71458 """1459 self._got_first_request = True14601461 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)14691470 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.14791480 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.14841485 :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 response15001501 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.15051506 .. 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 rv15131514 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.15191520 .. versionadded:: 0.101521 """1522 return False15231524 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.15281529 Override this method to change how the app runs async views.15301531 .. versionadded:: 2.01532 """1533 if iscoroutinefunction(func):1534 return self.async_to_sync(func)15351536 return func15371538 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.15421543 .. code-block:: python15441545 result = app.async_to_sync(func)(*args, **kwargs)15461547 Override this method to change how the app converts async code1548 to be synchronously callable.15491550 .. 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 None15581559 return asgiref_async_to_sync(func)15601561 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.15721573 This is called by :func:`flask.url_for`, and can be called1574 directly as well.15751576 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.15811582 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.15891590 Functions can be decorated with :meth:`url_defaults` to modify1591 keyword arguments before the URL is built.15921593 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.15971598 :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``.16131614 .. versionadded:: 2.21615 Moved from ``flask.url_for``, which calls this method.1616 """1617 req_ctx = _cv_request.get(None)16181619 if req_ctx is not None:1620 url_adapter = req_ctx.url_adapter1621 blueprint_name = req_ctx.request.blueprint16221623 # 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:]16301631 # 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)16371638 # 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)16451646 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 )16531654 # When outside a request, generate a URL with scheme and1655 # domain by default.1656 if _external is None:1657 _external = True16581659 # 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.")16631664 self.inject_url_defaults(endpoint, values)16651666 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)16791680 if _anchor is not None:1681 _anchor = _url_quote(_anchor, safe="%!#$&'()*+,/:;=?@")1682 rv = f"{rv}#{_anchor}"16831684 return rv16851686 def redirect(self, location: str, code: int = 302) -> BaseResponse:1687 """Create a redirect response object.16881689 This is called by :func:`flask.redirect`, and can be called1690 directly as well.16911692 :param location: The URL to redirect to.1693 :param code: The status code for the redirect.16941695 .. versionadded:: 2.21696 Moved from ``flask.redirect``, which calls this method.1697 """1698 return _wz_redirect(location, code=code, Response=self.response_class)16991700 def make_response(self, rv: ft.ResponseReturnValue) -> Response:1701 """Convert the return value from a view function to an instance of1702 :attr:`response_class`.17031704 :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``:17081709 ``str``1710 A response object is created with the string encoded to UTF-81711 as the body.17121713 ``bytes``1714 A response object is created with the bytes as the body.17151716 ``dict``1717 A dictionary that will be jsonify'd before being returned.17181719 ``list``1720 A list that will be jsonify'd before being returned.17211722 ``generator`` or ``iterator``1723 A generator that returns ``str`` or ``bytes`` to be1724 streamed as the response.17251726 ``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.17341735 :attr:`response_class`1736 The object is returned unchanged.17371738 other :class:`~werkzeug.wrappers.Response` class1739 The object is coerced to :attr:`response_class`.17401741 :func:`callable`1742 The function is called as a WSGI application. The result is1743 used to create a response object.17441745 .. versionchanged:: 2.21746 A generator will be converted to a streaming response.1747 A list will be converted to a JSON response.17481749 .. versionchanged:: 1.11750 A dict will be converted to a JSON response.17511752 .. versionchanged:: 0.91753 Previously a tuple was interpreted as the arguments for the1754 response object.1755 """17561757 status = headers = None17581759 # unpack tuple returns1760 if isinstance(rv, tuple):1761 len_rv = len(rv)17621763 # 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 )17791780 # 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 )17871788 # 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 )18251826 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 = status18331834 # extend existing headers with provided headers1835 if headers:1836 rv.headers.update(headers) # type: ignore[arg-type]18371838 return rv18391840 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.18441845 .. versionadded:: 0.618461847 .. versionchanged:: 0.91848 This can now also be called without a request object when the1849 URL adapter is created for the application context.18501851 .. 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 = None18631864 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 )18771878 return None18791880 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.18841885 .. versionadded:: 0.71886 """1887 names: t.Iterable[str | None] = (None,)18881889 # 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 )18951896 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)19001901 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.19081909 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``.19131914 :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 rv19271928 # Re-raise if called with an active exception, otherwise raise1929 # the passed in exception.1930 if error is sys.exc_info()[1]:1931 raise19321933 raise error19341935 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.19401941 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))19461947 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)19511952 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)()19561957 if rv is not None:1958 return rv19591960 return None19611962 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.19661967 .. versionchanged:: 0.51968 As of Flask 0.5 the functions registered for after request1969 execution are called in reverse order of registration.19701971 :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]19761977 for func in ctx._after_request_functions:1978 response = self.ensure_sync(func)(response)19791980 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)19841985 if not self.session_interface.is_null_session(ctx.session):1986 self.session_interface.save_session(self, ctx.session, response)19871988 return response19891990 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.19951996 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.20002001 This is called by2002 :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`,2003 which may be delayed during testing to maintain access to2004 resources.20052006 :param exc: An unhandled exception raised while dispatching the2007 request. Detected from the current exception information if2008 not passed. Passed to each teardown function.20092010 .. versionchanged:: 0.92011 Added the ``exc`` argument.2012 """2013 if exc is _sentinel:2014 exc = sys.exc_info()[1]20152016 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)20202021 request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)20222023 def do_teardown_appcontext(2024 self, exc: BaseException | None = _sentinel # type: ignore2025 ) -> None:2026 """Called right before the application context is popped.20272028 When handling a request, the application context is popped2029 after the request context. See :meth:`do_teardown_request`.20302031 This calls all functions decorated with2032 :meth:`teardown_appcontext`. Then the2033 :data:`appcontext_tearing_down` signal is sent.20342035 This is called by2036 :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.20372038 .. versionadded:: 0.92039 """2040 if exc is _sentinel:2041 exc = sys.exc_info()[1]20422043 for func in reversed(self.teardown_appcontext_funcs):2044 self.ensure_sync(func)(exc)20452046 appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)20472048 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.20522053 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.20572058 ::20592060 with app.app_context():2061 init_db()20622063 See :doc:`/appcontext`.20642065 .. versionadded:: 0.92066 """2067 return AppContext(self)20682069 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.20732074 See :doc:`/reqcontext`.20752076 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.20802081 :param environ: a WSGI environment2082 """2083 return RequestContext(self, environ)20842085 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.20902091 See :doc:`/reqcontext`.20922093 Use a ``with`` block to push the context, which will make2094 :data:`request` point at the request for the created2095 environment. ::20962097 with app.test_request_context(...):2098 generate_report()20992100 When using the shell, it may be easier to push and pop the2101 context manually to avoid indentation. ::21022103 ctx = app.test_request_context(...)2104 ctx.push()2105 ...2106 ctx.pop()21072108 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.21122113 :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 EnvironBuilder21332134 builder = EnvironBuilder(self, *args, **kwargs)21352136 try:2137 return self.request_context(builder.get_environ())2138 finally:2139 builder.close()21402141 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::21452146 app = MyMiddleware(app)21472148 It's a better idea to do this instead::21492150 app.wsgi_app = MyMiddleware(app.wsgi_app)21512152 Then you still have the original application object around and2153 can continue to call methods on it.21542155 .. 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`.21602161 :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())21832184 if error is not None and self.should_ignore_error(error):2185 error = None21862187 ctx.pop(error)21882189 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
1from __future__ import annotations23import os4import typing as t5from collections import defaultdict6from functools import update_wrapper78from . import typing as ft9from .scaffold import _endpoint_from_view_func10from .scaffold import _sentinel11from .scaffold import Scaffold12from .scaffold import setupmethod1314if t.TYPE_CHECKING: # pragma: no cover15 from .app import Flask1617DeferredSetupFunction = t.Callable[["BlueprintSetupState"], t.Callable]18T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable)19T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable)20T_error_handler = t.TypeVar("T_error_handler", bound=ft.ErrorHandlerCallable)21T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)22T_template_context_processor = t.TypeVar(23 "T_template_context_processor", bound=ft.TemplateContextProcessorCallable24)25T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable)26T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable)27T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable)28T_url_defaults = t.TypeVar("T_url_defaults", bound=ft.URLDefaultCallable)29T_url_value_preprocessor = t.TypeVar(30 "T_url_value_preprocessor", bound=ft.URLValuePreprocessorCallable31)323334class 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 """4041 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 = app5051 #: a reference to the blueprint that created this setup state.52 self.blueprint = blueprint5354 #: a dictionary with all options that were passed to the55 #: :meth:`~flask.Flask.register_blueprint` method.56 self.options = options5758 #: 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_registration6364 subdomain = self.options.get("subdomain")65 if subdomain is None:66 subdomain = self.blueprint.subdomain6768 #: The subdomain that the blueprint should be active for, ``None``69 #: otherwise.70 self.subdomain = subdomain7172 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_prefix7879 self.name = self.options.get("name", blueprint.name)80 self.name_prefix = self.options.get("name_prefix", "")8182 #: 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", ()))8687 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"))109110 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 )117118119class Blueprint(Scaffold):120 """Represents a blueprint, a collection of routes and other121 app-related functions that can be registered on a real application122 later.123124 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.128129 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.132133 See :doc:`/blueprints` for more information.134135 :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.163164 .. 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.168169 .. versionadded:: 0.7170 """171172 _got_registered_once = False173174 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 )194195 if not name:196 raise ValueError("'name' may not be empty.")197198 if "." in name:199 raise ValueError("'name' may not contain a dot '.' character.")200201 self.name = name202 self.url_prefix = url_prefix203 self.subdomain = subdomain204 self.deferred_functions: list[DeferredSetupFunction] = []205206 if url_defaults is None:207 url_defaults = {}208209 self.url_values_defaults = url_defaults210 self.cli_group = cli_group211 self._blueprints: list[tuple[Blueprint, dict]] = []212213 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 )222223 @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)231232 @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 """239240 def wrapper(state: BlueprintSetupState) -> None:241 if state.first_registration:242 func(state)243244 self.record(update_wrapper(wrapper, func))245246 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)254255 @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.260261 .. 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``.266267 .. versionadded:: 2.0268 """269 if blueprint is self:270 raise ValueError("Cannot register a blueprint on itself")271 self._blueprints.append((blueprint, options))272273 def register(self, app: 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.278279 :param app: The application this blueprint is being registered280 with.281 :param options: Keyword arguments forwarded from282 :meth:`~Flask.register_blueprint`.283284 .. versionchanged:: 2.3285 Nested blueprints now correctly apply subdomains.286287 .. versionchanged:: 2.1288 Registering the same blueprint with the same name multiple289 times is an error.290291 .. 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.295296 .. 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(".")305306 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 ""309310 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 )315316 first_bp_registration = not any(bp is self for bp in app.blueprints.values())317 first_name_registration = name not in app.blueprints318319 app.blueprints[name] = self320 self._got_registered_once = True321 state = self.make_setup_state(app, options, first_bp_registration)322323 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 )329330 # Merge blueprint data into parent.331 if first_bp_registration or first_name_registration:332333 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)337338 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] = value350351 for endpoint, func in self.view_functions.items():352 app.view_functions[endpoint] = func353354 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)363364 for deferred in self.deferred_functions:365 deferred(state)366367 cli_resolved_group = options.get("cli_group", self.cli_group)368369 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)378379 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")383384 if bp_subdomain is None:385 bp_subdomain = blueprint.subdomain386387 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.subdomain393394 if bp_url_prefix is None:395 bp_url_prefix = blueprint.url_prefix396397 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_prefix405406 bp_options["name_prefix"] = name407 blueprint.register(app, bp_options)408409 @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.420421 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.")426427 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.")429430 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 )439440 @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`.446447 :param name: the optional name of the filter, otherwise the448 function name will be used.449 """450451 def decorator(f: T_template_filter) -> T_template_filter:452 self.add_app_template_filter(f, name=name)453 return f454455 return decorator456457 @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`.464465 :param name: the optional name of the filter, otherwise the466 function name will be used.467 """468469 def register_template(state: BlueprintSetupState) -> None:470 state.app.jinja_env.filters[name or f.__name__] = f471472 self.record_once(register_template)473474 @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`.480481 .. versionadded:: 0.10482483 :param name: the optional name of the test, otherwise the484 function name will be used.485 """486487 def decorator(f: T_template_test) -> T_template_test:488 self.add_app_template_test(f, name=name)489 return f490491 return decorator492493 @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`.500501 .. versionadded:: 0.10502503 :param name: the optional name of the test, otherwise the504 function name will be used.505 """506507 def register_template(state: BlueprintSetupState) -> None:508 state.app.jinja_env.tests[name or f.__name__] = f509510 self.record_once(register_template)511512 @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`.518519 .. versionadded:: 0.10520521 :param name: the optional name of the global, otherwise the522 function name will be used.523 """524525 def decorator(f: T_template_global) -> T_template_global:526 self.add_app_template_global(f, name=name)527 return f528529 return decorator530531 @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`.538539 .. versionadded:: 0.10540541 :param name: the optional name of the global, otherwise the542 function name will be used.543 """544545 def register_template(state: BlueprintSetupState) -> None:546 state.app.jinja_env.globals[name or f.__name__] = f547548 self.record_once(register_template)549550 @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 f559560 @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 f569570 @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 f579580 @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 f591592 @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 """599600 def decorator(f: T_error_handler) -> T_error_handler:601 self.record_once(lambda s: s.app.errorhandler(code)(f))602 return f603604 return decorator605606 @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 f617618 @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 f
deleted:src/flask/scaffold.py-873 removed
1from __future__ import annotations23import importlib.util4import os5import pathlib6import sys7import typing as t8from collections import defaultdict9from datetime import timedelta10from functools import update_wrapper1112from jinja2 import FileSystemLoader13from werkzeug.exceptions import default_exceptions14from werkzeug.exceptions import HTTPException15from werkzeug.utils import cached_property1617from . import typing as ft18from .cli import AppGroup19from .globals import current_app20from .helpers import get_root_path21from .helpers import send_from_directory22from .templating import _default_template_ctx_processor2324if t.TYPE_CHECKING: # pragma: no cover25 from .wrappers import Response2627# a singleton sentinel value for parameter defaults28_sentinel = object()2930F = t.TypeVar("F", bound=t.Callable[..., t.Any])31T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable)32T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable)33T_error_handler = t.TypeVar("T_error_handler", bound=ft.ErrorHandlerCallable)34T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)35T_template_context_processor = t.TypeVar(36 "T_template_context_processor", bound=ft.TemplateContextProcessorCallable37)38T_url_defaults = t.TypeVar("T_url_defaults", bound=ft.URLDefaultCallable)39T_url_value_preprocessor = t.TypeVar(40 "T_url_value_preprocessor", bound=ft.URLValuePreprocessorCallable41)42T_route = t.TypeVar("T_route", bound=ft.RouteCallable)434445def setupmethod(f: F) -> F:46 f_name = f.__name__4748 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)5152 return t.cast(F, update_wrapper(wrapper_func, f))535455class Scaffold:56 """Common behavior shared between :class:`~flask.Flask` and57 :class:`~flask.blueprints.Blueprint`.5859 :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``.6970 .. versionadded:: 2.071 """7273 name: str74 _static_folder: str | None = None75 _static_url_path: str | None = None7677 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_name8889 self.static_folder = static_folder # type: ignore90 self.static_url_path = static_url_path9192 #: 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_folder9697 if root_path is None:98 root_path = get_root_path(self.import_name)99100 #: Absolute path to the package on the filesystem. Used to look101 #: up resources contained in the package.102 self.root_path = root_path103104 #: 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()109110 #: 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] = {}117118 #: 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))135136 #: 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)149150 #: 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)163164 #: 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)178179 #: 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]})193194 #: 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)209210 #: 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)224225 def __repr__(self) -> str:226 return f"<{type(self).__name__} {self.name!r}>"227228 def _check_setup_finished(self, f_name: str) -> None:229 raise NotImplementedError230231 @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 None240241 @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"\/")245246 self._static_folder = value247248 @property249 def has_static_folder(self) -> bool:250 """``True`` if :attr:`static_folder` is set.251252 .. versionadded:: 0.5253 """254 return self.static_folder is not None255256 @property257 def static_url_path(self) -> str | None:258 """The URL prefix that the static route will be accessible from.259260 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_path265266 if self.static_folder is not None:267 basename = os.path.basename(self.static_folder)268 return f"/{basename}".rstrip("/")269270 return None271272 @static_url_path.setter273 def static_url_path(self, value: str | None) -> None:274 if value is not None:275 value = value.rstrip("/")276277 self._static_url_path = value278279 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.282283 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.287288 .. versionchanged:: 2.0289 The default configuration is ``None`` instead of 12 hours.290291 .. versionadded:: 0.9292 """293 value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]294295 if value is None:296 return None297298 if isinstance(value, timedelta):299 return int(value.total_seconds())300301 return value302303 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.308309 .. versionadded:: 0.5310 """311 if not self.has_static_folder:312 raise RuntimeError("'static_folder' must be set to serve static_files.")313314 # 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 )320321 @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.326327 .. 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 None333334 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.337338 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:341342 .. code-block:: python343344 with app.open_resource("schema.sql") as f:345 conn.executescript(f.read())346347 :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.")354355 return open(os.path.join(self.root_path, resource), mode)356357 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.")365366 return self.route(rule, methods=[method], **options)367368 @setupmethod369 def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:370 """Shortcut for :meth:`route` with ``methods=["GET"]``.371372 .. versionadded:: 2.0373 """374 return self._method_route("GET", rule, options)375376 @setupmethod377 def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:378 """Shortcut for :meth:`route` with ``methods=["POST"]``.379380 .. versionadded:: 2.0381 """382 return self._method_route("POST", rule, options)383384 @setupmethod385 def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:386 """Shortcut for :meth:`route` with ``methods=["PUT"]``.387388 .. versionadded:: 2.0389 """390 return self._method_route("PUT", rule, options)391392 @setupmethod393 def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:394 """Shortcut for :meth:`route` with ``methods=["DELETE"]``.395396 .. versionadded:: 2.0397 """398 return self._method_route("DELETE", rule, options)399400 @setupmethod401 def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:402 """Shortcut for :meth:`route` with ``methods=["PATCH"]``.403404 .. versionadded:: 2.0405 """406 return self._method_route("PATCH", rule, options)407408 @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.413414 .. code-block:: python415416 @app.route("/")417 def index():418 return "Hello, World!"419420 See :ref:`url-route-registrations`.421422 The endpoint name for the route defaults to the name of the view423 function if the ``endpoint`` parameter isn't passed.424425 The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and426 ``OPTIONS`` are added automatically.427428 :param rule: The URL rule string.429 :param options: Extra options passed to the430 :class:`~werkzeug.routing.Rule` object.431 """432433 def decorator(f: T_route) -> T_route:434 endpoint = options.pop("endpoint", None)435 self.add_url_rule(rule, endpoint, f, **options)436 return f437438 return decorator439440 @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:452453 .. code-block:: python454455 @app.route("/")456 def index():457 ...458459 .. code-block:: python460461 def index():462 ...463464 app.add_url_rule("/", view_func=index)465466 See :ref:`url-route-registrations`.467468 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.472473 The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` is474 always added automatically, and ``OPTIONS`` is added475 automatically by default.476477 ``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.481482 .. code-block:: python483484 app.add_url_rule("/", endpoint="index")485486 @app.endpoint("index")487 def index():488 ...489490 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.494495 :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 NotImplementedError507508 @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`.513514 .. code-block:: python515516 app.add_url_rule("/ex", endpoint="example")517518 @app.endpoint("example")519 def example():520 ...521522 :param endpoint: The endpoint name to associate with the view523 function.524 """525526 def decorator(f: F) -> F:527 self.view_functions[endpoint] = f528 return f529530 return decorator531532 @setupmethod533 def before_request(self, f: T_before_request) -> T_before_request:534 """Register a function to run before each request.535536 For example, this can be used to open a database connection, or537 to load the logged in user from the session.538539 .. code-block:: python540541 @app.before_request542 def load_user():543 if "user_id" in session:544 g.user = db.session.get(session["user_id"])545546 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.550551 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 f558559 @setupmethod560 def after_request(self, f: T_after_request) -> T_after_request:561 """Register a function to run after each request to this object.562563 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.566567 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.571572 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 f579580 @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.585586 .. code-block:: python587588 with app.test_request_context():589 ...590591 When the ``with`` block exits (or ``ctx.pop()`` is called), the592 teardown functions are called just before the request context is593 made inactive.594595 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.599600 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.603604 The return values of teardown functions are ignored.605606 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 f613614 @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.622623 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 f630631 @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.639640 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.644645 The function is passed the endpoint name and values dict. The return646 value is ignored.647648 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 f655656 @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.661662 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 f669670 @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.675676 A decorator that is used to register a function given an677 error code. Example::678679 @app.errorhandler(404)680 def page_not_found(error):681 return 'This page does not exist', 404682683 You can also register handlers for arbitrary exceptions::684685 @app.errorhandler(DatabaseError)686 def special_exception_handler(error):687 return 'Database connection failed', 500688689 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`.693694 .. versionadded:: 0.7695 Use :meth:`register_error_handler` instead of modifying696 :attr:`error_handler_spec` directly, for application wide error697 handlers.698699 .. 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.703704 :param code_or_exception: the code as integer for the handler, or705 an arbitrary exception706 """707708 def decorator(f: T_error_handler) -> T_error_handler:709 self.register_error_handler(code_or_exception, f)710 return f711712 return decorator713714 @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.723724 .. 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] = f728729 @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.736737 :param exc_class_or_code: Any exception class, or an HTTP status738 code as an integer.739 """740 exc_class: type[Exception]741742 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_code753754 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 )760761 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 )767768 if issubclass(exc_class, HTTPException):769 return exc_class, exc_class.code770 else:771 return exc_class, None772773774def _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__780781782def _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 False789790791def _find_package_path(import_name):792 """Find the path that contains the package or module."""793 root_mod_name, _, _ = import_name.partition(".")794795 try:796 root_spec = importlib.util.find_spec(root_mod_name)797798 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()807808 if root_spec.origin in {"namespace", None}:809 # namespace package810 package_spec = importlib.util.find_spec(import_name)811812 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]825826 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)833834835def find_package(import_name: str):836 """Find the prefix that a package is installed under, and the path837 that it would be imported from.838839 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.843844 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)850851 # installed to the system852 if _path_is_relative_to(pathlib.PurePath(package_path), py_prefix):853 return py_prefix, package_path854855 site_parent, site_folder = os.path.split(package_path)856857 # installed to a virtualenv858 if site_folder.lower() == "site-packages":859 parent, folder = os.path.split(site_parent)860861 # Windows (prefix/lib/site-packages)862 if folder.lower() == "lib":863 return parent, package_path864865 # Unix (prefix/lib/pythonX.Y/site-packages)866 if os.path.basename(parent).lower() == "lib":867 return os.path.dirname(parent), package_path868869 # something else (prefix/site-packages)870 return site_parent, package_path871872 # not installed873 return None, package_path