Skip to content
Myr

Split the App and Blueprint into Sansio and IO parts (#5127)

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

authored by David Lord · committed by GitHub · parents 0e0e8dd, bc5dd38 · Browse files · 14 files+2617 added−2334 removed
This commit

State

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

Diff stats

14 files+2617 added−2334 removed

  • other:+2617 added−2334 removed

14 files+2617 added−2334 removed

modified:src/flask/json/provider.py+2 added-2 removed
9 unmodified lines
1011from werkzeug.http import http_date1213if t.TYPE_CHECKING: # pragma: no cover14 from ..app import Flask14 from ..sansio.app import App15 from ..wrappers import Response161718class JSONProvider:
14 unmodified lines
3334 .. versionadded:: 2.235 """3637 def __init__(self, app: Flask) -> None:37 def __init__(self, app: App) -> None:38 self._app = weakref.proxy(app)3940 def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:41 """Serialize data as JSON.
175 unmodified lines
added:src/flask/sansio/app.py+964 added
1from __future__ import annotations23import logging4import os5import sys6import typing as t7from datetime import timedelta8from itertools import chain910from werkzeug.exceptions import Aborter11from werkzeug.exceptions import BadRequest12from werkzeug.exceptions import BadRequestKeyError13from werkzeug.routing import BuildError14from werkzeug.routing import Map15from werkzeug.routing import Rule16from werkzeug.sansio.response import Response17from werkzeug.utils import cached_property18from werkzeug.utils import redirect as _wz_redirect1920from .. import typing as ft21from ..config import Config22from ..config import ConfigAttribute23from ..ctx import _AppCtxGlobals24from ..helpers import _split_blueprint_path25from ..helpers import get_debug_flag26from ..json.provider import DefaultJSONProvider27from ..json.provider import JSONProvider28from ..logging import create_logger29from ..templating import DispatchingJinjaLoader30from ..templating import Environment31from .scaffold import _endpoint_from_view_func32from .scaffold import find_package33from .scaffold import Scaffold34from .scaffold import setupmethod3536if t.TYPE_CHECKING: # pragma: no cover37 from werkzeug.wrappers import Response as BaseResponse38 from .blueprints import Blueprint39 from ..testing import FlaskClient40 from ..testing import FlaskCliRunner4142T_shell_context_processor = t.TypeVar(43 "T_shell_context_processor", bound=ft.ShellContextProcessorCallable44)45T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)46T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable)47T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable)48T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable)495051def _make_timedelta(value: timedelta | int | None) -> timedelta | None:52 if value is None or isinstance(value, timedelta):53 return value5455 return timedelta(seconds=value)565758class App(Scaffold):59 """The flask object implements a WSGI application and acts as the central60 object. It is passed the name of the module or package of the61 application. Once it is created it will act as a central registry for62 the view functions, the URL rules, template configuration and much more.6364 The name of the package is used to resolve resources from inside the65 package or the folder the module is contained in depending on if the66 package parameter resolves to an actual python package (a folder with67 an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).6869 For more information about resource loading, see :func:`open_resource`.7071 Usually you create a :class:`Flask` instance in your main module or72 in the :file:`__init__.py` file of your package like this::7374 from flask import Flask75 app = Flask(__name__)7677 .. admonition:: About the First Parameter7879 The idea of the first parameter is to give Flask an idea of what80 belongs to your application. This name is used to find resources81 on the filesystem, can be used by extensions to improve debugging82 information and a lot more.8384 So it's important what you provide there. If you are using a single85 module, `__name__` is always the correct value. If you however are86 using a package, it's usually recommended to hardcode the name of87 your package there.8889 For example if your application is defined in :file:`yourapplication/app.py`90 you should create it with one of the two versions below::9192 app = Flask('yourapplication')93 app = Flask(__name__.split('.')[0])9495 Why is that? The application will work even with `__name__`, thanks96 to how resources are looked up. However it will make debugging more97 painful. Certain extensions can make assumptions based on the98 import name of your application. For example the Flask-SQLAlchemy99 extension will look for the code in your application that triggered100 an SQL query in debug mode. If the import name is not properly set101 up, that debugging information is lost. (For example it would only102 pick up SQL queries in `yourapplication.app` and not103 `yourapplication.views.frontend`)104105 .. versionadded:: 0.7106 The `static_url_path`, `static_folder`, and `template_folder`107 parameters were added.108109 .. versionadded:: 0.8110 The `instance_path` and `instance_relative_config` parameters were111 added.112113 .. versionadded:: 0.11114 The `root_path` parameter was added.115116 .. versionadded:: 1.0117 The ``host_matching`` and ``static_host`` parameters were added.118119 .. versionadded:: 1.0120 The ``subdomain_matching`` parameter was added. Subdomain121 matching needs to be enabled manually now. Setting122 :data:`SERVER_NAME` does not implicitly enable it.123124 :param import_name: the name of the application package125 :param static_url_path: can be used to specify a different path for the126 static files on the web. Defaults to the name127 of the `static_folder` folder.128 :param static_folder: The folder with static files that is served at129 ``static_url_path``. Relative to the application ``root_path``130 or an absolute path. Defaults to ``'static'``.131 :param static_host: the host to use when adding the static route.132 Defaults to None. Required when using ``host_matching=True``133 with a ``static_folder`` configured.134 :param host_matching: set ``url_map.host_matching`` attribute.135 Defaults to False.136 :param subdomain_matching: consider the subdomain relative to137 :data:`SERVER_NAME` when matching routes. Defaults to False.138 :param template_folder: the folder that contains the templates that should139 be used by the application. Defaults to140 ``'templates'`` folder in the root path of the141 application.142 :param instance_path: An alternative instance path for the application.143 By default the folder ``'instance'`` next to the144 package or module is assumed to be the instance145 path.146 :param instance_relative_config: if set to ``True`` relative filenames147 for loading the config are assumed to148 be relative to the instance path instead149 of the application root.150 :param root_path: The path to the root of the application files.151 This should only be set manually when it can't be detected152 automatically, such as for namespace packages.153 """154155 #: The class of the object assigned to :attr:`aborter`, created by156 #: :meth:`create_aborter`. That object is called by157 #: :func:`flask.abort` to raise HTTP errors, and can be158 #: called directly as well.159 #:160 #: Defaults to :class:`werkzeug.exceptions.Aborter`.161 #:162 #: .. versionadded:: 2.2163 aborter_class = Aborter164165 #: The class that is used for the Jinja environment.166 #:167 #: .. versionadded:: 0.11168 jinja_environment = Environment169170 #: The class that is used for the :data:`~flask.g` instance.171 #:172 #: Example use cases for a custom class:173 #:174 #: 1. Store arbitrary attributes on flask.g.175 #: 2. Add a property for lazy per-request database connectors.176 #: 3. Return None instead of AttributeError on unexpected attributes.177 #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g.178 #:179 #: In Flask 0.9 this property was called `request_globals_class` but it180 #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the181 #: flask.g object is now application context scoped.182 #:183 #: .. versionadded:: 0.10184 app_ctx_globals_class = _AppCtxGlobals185186 #: The class that is used for the ``config`` attribute of this app.187 #: Defaults to :class:`~flask.Config`.188 #:189 #: Example use cases for a custom class:190 #:191 #: 1. Default values for certain config options.192 #: 2. Access to config values through attributes in addition to keys.193 #:194 #: .. versionadded:: 0.11195 config_class = Config196197 #: The testing flag. Set this to ``True`` to enable the test mode of198 #: Flask extensions (and in the future probably also Flask itself).199 #: For example this might activate test helpers that have an200 #: additional runtime cost which should not be enabled by default.201 #:202 #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the203 #: default it's implicitly enabled.204 #:205 #: This attribute can also be configured from the config with the206 #: ``TESTING`` configuration key. Defaults to ``False``.207 testing = ConfigAttribute("TESTING")208209 #: If a secret key is set, cryptographic components can use this to210 #: sign cookies and other things. Set this to a complex random value211 #: when you want to use the secure cookie for instance.212 #:213 #: This attribute can also be configured from the config with the214 #: :data:`SECRET_KEY` configuration key. Defaults to ``None``.215 secret_key = ConfigAttribute("SECRET_KEY")216217 #: A :class:`~datetime.timedelta` which is used to set the expiration218 #: date of a permanent session. The default is 31 days which makes a219 #: permanent session survive for roughly one month.220 #:221 #: This attribute can also be configured from the config with the222 #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to223 #: ``timedelta(days=31)``224 permanent_session_lifetime = ConfigAttribute(225 "PERMANENT_SESSION_LIFETIME", get_converter=_make_timedelta226 )227228 json_provider_class: type[JSONProvider] = DefaultJSONProvider229 """A subclass of :class:`~flask.json.provider.JSONProvider`. An230 instance is created and assigned to :attr:`app.json` when creating231 the app.232233 The default, :class:`~flask.json.provider.DefaultJSONProvider`, uses234 Python's built-in :mod:`json` library. A different provider can use235 a different JSON library.236237 .. versionadded:: 2.2238 """239240 #: Options that are passed to the Jinja environment in241 #: :meth:`create_jinja_environment`. Changing these options after242 #: the environment is created (accessing :attr:`jinja_env`) will243 #: have no effect.244 #:245 #: .. versionchanged:: 1.1.0246 #: This is a ``dict`` instead of an ``ImmutableDict`` to allow247 #: easier configuration.248 #:249 jinja_options: dict = {}250251 #: The rule object to use for URL rules created. This is used by252 #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.253 #:254 #: .. versionadded:: 0.7255 url_rule_class = Rule256257 #: The map object to use for storing the URL rules and routing258 #: configuration parameters. Defaults to :class:`werkzeug.routing.Map`.259 #:260 #: .. versionadded:: 1.1.0261 url_map_class = Map262263 #: The :meth:`test_client` method creates an instance of this test264 #: client class. Defaults to :class:`~flask.testing.FlaskClient`.265 #:266 #: .. versionadded:: 0.7267 test_client_class: type[FlaskClient] | None = None268269 #: The :class:`~click.testing.CliRunner` subclass, by default270 #: :class:`~flask.testing.FlaskCliRunner` that is used by271 #: :meth:`test_cli_runner`. Its ``__init__`` method should take a272 #: Flask app object as the first argument.273 #:274 #: .. versionadded:: 1.0275 test_cli_runner_class: type[FlaskCliRunner] | None = None276277 default_config: dict278 response_class: type[Response]279280 def __init__(281 self,282 import_name: str,283 static_url_path: str | None = None,284 static_folder: str | os.PathLike | None = "static",285 static_host: str | None = None,286 host_matching: bool = False,287 subdomain_matching: bool = False,288 template_folder: str | os.PathLike | None = "templates",289 instance_path: str | None = None,290 instance_relative_config: bool = False,291 root_path: str | None = None,292 ):293 super().__init__(294 import_name=import_name,295 static_folder=static_folder,296 static_url_path=static_url_path,297 template_folder=template_folder,298 root_path=root_path,299 )300301 if instance_path is None:302 instance_path = self.auto_find_instance_path()303 elif not os.path.isabs(instance_path):304 raise ValueError(305 "If an instance path is provided it must be absolute."306 " A relative path was given instead."307 )308309 #: Holds the path to the instance folder.310 #:311 #: .. versionadded:: 0.8312 self.instance_path = instance_path313314 #: The configuration dictionary as :class:`Config`. This behaves315 #: exactly like a regular dictionary but supports additional methods316 #: to load a config from files.317 self.config = self.make_config(instance_relative_config)318319 #: An instance of :attr:`aborter_class` created by320 #: :meth:`make_aborter`. This is called by :func:`flask.abort`321 #: to raise HTTP errors, and can be called directly as well.322 #:323 #: .. versionadded:: 2.2324 #: Moved from ``flask.abort``, which calls this object.325 self.aborter = self.make_aborter()326327 self.json: JSONProvider = self.json_provider_class(self)328 """Provides access to JSON methods. Functions in ``flask.json``329 will call methods on this provider when the application context330 is active. Used for handling JSON requests and responses.331332 An instance of :attr:`json_provider_class`. Can be customized by333 changing that attribute on a subclass, or by assigning to this334 attribute afterwards.335336 The default, :class:`~flask.json.provider.DefaultJSONProvider`,337 uses Python's built-in :mod:`json` library. A different provider338 can use a different JSON library.339340 .. versionadded:: 2.2341 """342343 #: A list of functions that are called by344 #: :meth:`handle_url_build_error` when :meth:`.url_for` raises a345 #: :exc:`~werkzeug.routing.BuildError`. Each function is called346 #: with ``error``, ``endpoint`` and ``values``. If a function347 #: returns ``None`` or raises a ``BuildError``, it is skipped.348 #: Otherwise, its return value is returned by ``url_for``.349 #:350 #: .. versionadded:: 0.9351 self.url_build_error_handlers: list[352 t.Callable[[Exception, str, dict[str, t.Any]], str]353 ] = []354355 #: A list of functions that are called when the application context356 #: is destroyed. Since the application context is also torn down357 #: if the request ends this is the place to store code that disconnects358 #: from databases.359 #:360 #: .. versionadded:: 0.9361 self.teardown_appcontext_funcs: list[ft.TeardownCallable] = []362363 #: A list of shell context processor functions that should be run364 #: when a shell context is created.365 #:366 #: .. versionadded:: 0.11367 self.shell_context_processors: list[ft.ShellContextProcessorCallable] = []368369 #: Maps registered blueprint names to blueprint objects. The370 #: dict retains the order the blueprints were registered in.371 #: Blueprints can be registered multiple times, this dict does372 #: not track how often they were attached.373 #:374 #: .. versionadded:: 0.7375 self.blueprints: dict[str, Blueprint] = {}376377 #: a place where extensions can store application specific state. For378 #: example this is where an extension could store database engines and379 #: similar things.380 #:381 #: The key must match the name of the extension module. For example in382 #: case of a "Flask-Foo" extension in `flask_foo`, the key would be383 #: ``'foo'``.384 #:385 #: .. versionadded:: 0.7386 self.extensions: dict = {}387388 #: The :class:`~werkzeug.routing.Map` for this instance. You can use389 #: this to change the routing converters after the class was created390 #: but before any routes are connected. Example::391 #:392 #: from werkzeug.routing import BaseConverter393 #:394 #: class ListConverter(BaseConverter):395 #: def to_python(self, value):396 #: return value.split(',')397 #: def to_url(self, values):398 #: return ','.join(super(ListConverter, self).to_url(value)399 #: for value in values)400 #:401 #: app = Flask(__name__)402 #: app.url_map.converters['list'] = ListConverter403 self.url_map = self.url_map_class(host_matching=host_matching)404405 self.subdomain_matching = subdomain_matching406407 # tracks internally if the application already handled at least one408 # request.409 self._got_first_request = False410411 # Set the name of the Click group in case someone wants to add412 # the app's commands to another CLI tool.413 self.cli.name = self.name414415 def _check_setup_finished(self, f_name: str) -> None:416 if self._got_first_request:417 raise AssertionError(418 f"The setup method '{f_name}' can no longer be called"419 " on the application. It has already handled its first"420 " request, any changes will not be applied"421 " consistently.\n"422 "Make sure all imports, decorators, functions, etc."423 " needed to set up the application are done before"424 " running it."425 )426427 @cached_property428 def name(self) -> str: # type: ignore429 """The name of the application. This is usually the import name430 with the difference that it's guessed from the run file if the431 import name is main. This name is used as a display name when432 Flask needs the name of the application. It can be set and overridden433 to change the value.434435 .. versionadded:: 0.8436 """437 if self.import_name == "__main__":438 fn = getattr(sys.modules["__main__"], "__file__", None)439 if fn is None:440 return "__main__"441 return os.path.splitext(os.path.basename(fn))[0]442 return self.import_name443444 @cached_property445 def logger(self) -> logging.Logger:446 """A standard Python :class:`~logging.Logger` for the app, with447 the same name as :attr:`name`.448449 In debug mode, the logger's :attr:`~logging.Logger.level` will450 be set to :data:`~logging.DEBUG`.451452 If there are no handlers configured, a default handler will be453 added. See :doc:`/logging` for more information.454455 .. versionchanged:: 1.1.0456 The logger takes the same name as :attr:`name` rather than457 hard-coding ``"flask.app"``.458459 .. versionchanged:: 1.0.0460 Behavior was simplified. The logger is always named461 ``"flask.app"``. The level is only set during configuration,462 it doesn't check ``app.debug`` each time. Only one format is463 used, not different ones depending on ``app.debug``. No464 handlers are removed, and a handler is only added if no465 handlers are already configured.466467 .. versionadded:: 0.3468 """469 return create_logger(self)470471 @cached_property472 def jinja_env(self) -> Environment:473 """The Jinja environment used to load templates.474475 The environment is created the first time this property is476 accessed. Changing :attr:`jinja_options` after that will have no477 effect.478 """479 return self.create_jinja_environment()480481 def create_jinja_environment(self) -> Environment:482 raise NotImplementedError()483484 def make_config(self, instance_relative: bool = False) -> Config:485 """Used to create the config attribute by the Flask constructor.486 The `instance_relative` parameter is passed in from the constructor487 of Flask (there named `instance_relative_config`) and indicates if488 the config should be relative to the instance path or the root path489 of the application.490491 .. versionadded:: 0.8492 """493 root_path = self.root_path494 if instance_relative:495 root_path = self.instance_path496 defaults = dict(self.default_config)497 defaults["DEBUG"] = get_debug_flag()498 return self.config_class(root_path, defaults)499500 def make_aborter(self) -> Aborter:501 """Create the object to assign to :attr:`aborter`. That object502 is called by :func:`flask.abort` to raise HTTP errors, and can503 be called directly as well.504505 By default, this creates an instance of :attr:`aborter_class`,506 which defaults to :class:`werkzeug.exceptions.Aborter`.507508 .. versionadded:: 2.2509 """510 return self.aborter_class()511512 def auto_find_instance_path(self) -> str:513 """Tries to locate the instance path if it was not provided to the514 constructor of the application class. It will basically calculate515 the path to a folder named ``instance`` next to your main file or516 the package.517518 .. versionadded:: 0.8519 """520 prefix, package_path = find_package(self.import_name)521 if prefix is None:522 return os.path.join(package_path, "instance")523 return os.path.join(prefix, "var", f"{self.name}-instance")524525 def create_global_jinja_loader(self) -> DispatchingJinjaLoader:526 """Creates the loader for the Jinja2 environment. Can be used to527 override just the loader and keeping the rest unchanged. It's528 discouraged to override this function. Instead one should override529 the :meth:`jinja_loader` function instead.530531 The global loader dispatches between the loaders of the application532 and the individual blueprints.533534 .. versionadded:: 0.7535 """536 return DispatchingJinjaLoader(self)537538 def select_jinja_autoescape(self, filename: str) -> bool:539 """Returns ``True`` if autoescaping should be active for the given540 template name. If no template name is given, returns `True`.541542 .. versionchanged:: 2.2543 Autoescaping is now enabled by default for ``.svg`` files.544545 .. versionadded:: 0.5546 """547 if filename is None:548 return True549 return filename.endswith((".html", ".htm", ".xml", ".xhtml", ".svg"))550551 @property552 def debug(self) -> bool:553 """Whether debug mode is enabled. When using ``flask run`` to start the554 development server, an interactive debugger will be shown for unhandled555 exceptions, and the server will be reloaded when code changes. This maps to the556 :data:`DEBUG` config key. It may not behave as expected if set late.557558 **Do not enable debug mode when deploying in production.**559560 Default: ``False``561 """562 return self.config["DEBUG"]563564 @debug.setter565 def debug(self, value: bool) -> None:566 self.config["DEBUG"] = value567568 if self.config["TEMPLATES_AUTO_RELOAD"] is None:569 self.jinja_env.auto_reload = value570571 @setupmethod572 def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:573 """Register a :class:`~flask.Blueprint` on the application. Keyword574 arguments passed to this method will override the defaults set on the575 blueprint.576577 Calls the blueprint's :meth:`~flask.Blueprint.register` method after578 recording the blueprint in the application's :attr:`blueprints`.579580 :param blueprint: The blueprint to register.581 :param url_prefix: Blueprint routes will be prefixed with this.582 :param subdomain: Blueprint routes will match on this subdomain.583 :param url_defaults: Blueprint routes will use these default values for584 view arguments.585 :param options: Additional keyword arguments are passed to586 :class:`~flask.blueprints.BlueprintSetupState`. They can be587 accessed in :meth:`~flask.Blueprint.record` callbacks.588589 .. versionchanged:: 2.0.1590 The ``name`` option can be used to change the (pre-dotted)591 name the blueprint is registered with. This allows the same592 blueprint to be registered multiple times with unique names593 for ``url_for``.594595 .. versionadded:: 0.7596 """597 blueprint.register(self, options)598599 def iter_blueprints(self) -> t.ValuesView[Blueprint]:600 """Iterates over all blueprints by the order they were registered.601602 .. versionadded:: 0.11603 """604 return self.blueprints.values()605606 @setupmethod607 def add_url_rule(608 self,609 rule: str,610 endpoint: str | None = None,611 view_func: ft.RouteCallable | None = None,612 provide_automatic_options: bool | None = None,613 **options: t.Any,614 ) -> None:615 if endpoint is None:616 endpoint = _endpoint_from_view_func(view_func) # type: ignore617 options["endpoint"] = endpoint618 methods = options.pop("methods", None)619620 # if the methods are not given and the view_func object knows its621 # methods we can use that instead. If neither exists, we go with622 # a tuple of only ``GET`` as default.623 if methods is None:624 methods = getattr(view_func, "methods", None) or ("GET",)625 if isinstance(methods, str):626 raise TypeError(627 "Allowed methods must be a list of strings, for"628 ' example: @app.route(..., methods=["POST"])'629 )630 methods = {item.upper() for item in methods}631632 # Methods that should always be added633 required_methods = set(getattr(view_func, "required_methods", ()))634635 # starting with Flask 0.8 the view_func object can disable and636 # force-enable the automatic options handling.637 if provide_automatic_options is None:638 provide_automatic_options = getattr(639 view_func, "provide_automatic_options", None640 )641642 if provide_automatic_options is None:643 if "OPTIONS" not in methods:644 provide_automatic_options = True645 required_methods.add("OPTIONS")646 else:647 provide_automatic_options = False648649 # Add the required methods now.650 methods |= required_methods651652 rule = self.url_rule_class(rule, methods=methods, **options)653 rule.provide_automatic_options = provide_automatic_options # type: ignore654655 self.url_map.add(rule)656 if view_func is not None:657 old_func = self.view_functions.get(endpoint)658 if old_func is not None and old_func != view_func:659 raise AssertionError(660 "View function mapping is overwriting an existing"661 f" endpoint function: {endpoint}"662 )663 self.view_functions[endpoint] = view_func664665 @setupmethod666 def template_filter(667 self, name: str | None = None668 ) -> t.Callable[[T_template_filter], T_template_filter]:669 """A decorator that is used to register custom template filter.670 You can specify a name for the filter, otherwise the function671 name will be used. Example::672673 @app.template_filter()674 def reverse(s):675 return s[::-1]676677 :param name: the optional name of the filter, otherwise the678 function name will be used.679 """680681 def decorator(f: T_template_filter) -> T_template_filter:682 self.add_template_filter(f, name=name)683 return f684685 return decorator686687 @setupmethod688 def add_template_filter(689 self, f: ft.TemplateFilterCallable, name: str | None = None690 ) -> None:691 """Register a custom template filter. Works exactly like the692 :meth:`template_filter` decorator.693694 :param name: the optional name of the filter, otherwise the695 function name will be used.696 """697 self.jinja_env.filters[name or f.__name__] = f698699 @setupmethod700 def template_test(701 self, name: str | None = None702 ) -> t.Callable[[T_template_test], T_template_test]:703 """A decorator that is used to register custom template test.704 You can specify a name for the test, otherwise the function705 name will be used. Example::706707 @app.template_test()708 def is_prime(n):709 if n == 2:710 return True711 for i in range(2, int(math.ceil(math.sqrt(n))) + 1):712 if n % i == 0:713 return False714 return True715716 .. versionadded:: 0.10717718 :param name: the optional name of the test, otherwise the719 function name will be used.720 """721722 def decorator(f: T_template_test) -> T_template_test:723 self.add_template_test(f, name=name)724 return f725726 return decorator727728 @setupmethod729 def add_template_test(730 self, f: ft.TemplateTestCallable, name: str | None = None731 ) -> None:732 """Register a custom template test. Works exactly like the733 :meth:`template_test` decorator.734735 .. versionadded:: 0.10736737 :param name: the optional name of the test, otherwise the738 function name will be used.739 """740 self.jinja_env.tests[name or f.__name__] = f741742 @setupmethod743 def template_global(744 self, name: str | None = None745 ) -> t.Callable[[T_template_global], T_template_global]:746 """A decorator that is used to register a custom template global function.747 You can specify a name for the global function, otherwise the function748 name will be used. Example::749750 @app.template_global()751 def double(n):752 return 2 * n753754 .. versionadded:: 0.10755756 :param name: the optional name of the global function, otherwise the757 function name will be used.758 """759760 def decorator(f: T_template_global) -> T_template_global:761 self.add_template_global(f, name=name)762 return f763764 return decorator765766 @setupmethod767 def add_template_global(768 self, f: ft.TemplateGlobalCallable, name: str | None = None769 ) -> None:770 """Register a custom template global function. Works exactly like the771 :meth:`template_global` decorator.772773 .. versionadded:: 0.10774775 :param name: the optional name of the global function, otherwise the776 function name will be used.777 """778 self.jinja_env.globals[name or f.__name__] = f779780 @setupmethod781 def teardown_appcontext(self, f: T_teardown) -> T_teardown:782 """Registers a function to be called when the application783 context is popped. The application context is typically popped784 after the request context for each request, at the end of CLI785 commands, or after a manually pushed context ends.786787 .. code-block:: python788789 with app.app_context():790 ...791792 When the ``with`` block exits (or ``ctx.pop()`` is called), the793 teardown functions are called just before the app context is794 made inactive. Since a request context typically also manages an795 application context it would also be called when you pop a796 request context.797798 When a teardown function was called because of an unhandled799 exception it will be passed an error object. If an800 :meth:`errorhandler` is registered, it will handle the exception801 and the teardown will not receive it.802803 Teardown functions must avoid raising exceptions. If they804 execute code that might fail they must surround that code with a805 ``try``/``except`` block and log any errors.806807 The return values of teardown functions are ignored.808809 .. versionadded:: 0.9810 """811 self.teardown_appcontext_funcs.append(f)812 return f813814 @setupmethod815 def shell_context_processor(816 self, f: T_shell_context_processor817 ) -> T_shell_context_processor:818 """Registers a shell context processor function.819820 .. versionadded:: 0.11821 """822 self.shell_context_processors.append(f)823 return f824825 def _find_error_handler(826 self, e: Exception, blueprints: list[str]827 ) -> ft.ErrorHandlerCallable | None:828 """Return a registered error handler for an exception in this order:829 blueprint handler for a specific code, app handler for a specific code,830 blueprint handler for an exception class, app handler for an exception831 class, or ``None`` if a suitable handler is not found.832 """833 exc_class, code = self._get_exc_class_and_code(type(e))834 names = (*blueprints, None)835836 for c in (code, None) if code is not None else (None,):837 for name in names:838 handler_map = self.error_handler_spec[name][c]839840 if not handler_map:841 continue842843 for cls in exc_class.__mro__:844 handler = handler_map.get(cls)845846 if handler is not None:847 return handler848 return None849850 def trap_http_exception(self, e: Exception) -> bool:851 """Checks if an HTTP exception should be trapped or not. By default852 this will return ``False`` for all exceptions except for a bad request853 key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It854 also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.855856 This is called for all HTTP exceptions raised by a view function.857 If it returns ``True`` for any exception the error handler for this858 exception is not called and it shows up as regular exception in the859 traceback. This is helpful for debugging implicitly raised HTTP860 exceptions.861862 .. versionchanged:: 1.0863 Bad request errors are not trapped by default in debug mode.864865 .. versionadded:: 0.8866 """867 if self.config["TRAP_HTTP_EXCEPTIONS"]:868 return True869870 trap_bad_request = self.config["TRAP_BAD_REQUEST_ERRORS"]871872 # if unset, trap key errors in debug mode873 if (874 trap_bad_request is None875 and self.debug876 and isinstance(e, BadRequestKeyError)877 ):878 return True879880 if trap_bad_request:881 return isinstance(e, BadRequest)882883 return False884885 def should_ignore_error(self, error: BaseException | None) -> bool:886 """This is called to figure out if an error should be ignored887 or not as far as the teardown system is concerned. If this888 function returns ``True`` then the teardown handlers will not be889 passed the error.890891 .. versionadded:: 0.10892 """893 return False894895 def redirect(self, location: str, code: int = 302) -> BaseResponse:896 """Create a redirect response object.897898 This is called by :func:`flask.redirect`, and can be called899 directly as well.900901 :param location: The URL to redirect to.902 :param code: The status code for the redirect.903904 .. versionadded:: 2.2905 Moved from ``flask.redirect``, which calls this method.906 """907 return _wz_redirect(908 location, code=code, Response=self.response_class # type: ignore[arg-type]909 )910911 def inject_url_defaults(self, endpoint: str, values: dict) -> None:912 """Injects the URL defaults for the given endpoint directly into913 the values dictionary passed. This is used internally and914 automatically called on URL building.915916 .. versionadded:: 0.7917 """918 names: t.Iterable[str | None] = (None,)919920 # url_for may be called outside a request context, parse the921 # passed endpoint instead of using request.blueprints.922 if "." in endpoint:923 names = chain(924 names, reversed(_split_blueprint_path(endpoint.rpartition(".")[0]))925 )926927 for name in names:928 if name in self.url_default_functions:929 for func in self.url_default_functions[name]:930 func(endpoint, values)931932 def handle_url_build_error(933 self, error: BuildError, endpoint: str, values: dict[str, t.Any]934 ) -> str:935 """Called by :meth:`.url_for` if a936 :exc:`~werkzeug.routing.BuildError` was raised. If this returns937 a value, it will be returned by ``url_for``, otherwise the error938 will be re-raised.939940 Each function in :attr:`url_build_error_handlers` is called with941 ``error``, ``endpoint`` and ``values``. If a function returns942 ``None`` or raises a ``BuildError``, it is skipped. Otherwise,943 its return value is returned by ``url_for``.944945 :param error: The active ``BuildError`` being handled.946 :param endpoint: The endpoint being built.947 :param values: The keyword arguments passed to ``url_for``.948 """949 for handler in self.url_build_error_handlers:950 try:951 rv = handler(error, endpoint, values)952 except BuildError as e:953 # make error available outside except block954 error = e955 else:956 if rv is not None:957 return rv958959 # Re-raise if called with an active exception, otherwise raise960 # the passed in exception.961 if error is sys.exc_info()[1]:962 raise963964 raise error
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 App1617DeferredSetupFunction = 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: App,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: App, options: dict, first_registration: bool = False248 ) -> BlueprintSetupState:249 """Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`250 object that is later passed to the register callback functions.251 Subclasses can override this to return a subclass of the setup state.252 """253 return BlueprintSetupState(self, app, options, first_registration)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: App, options: dict) -> None:274 """Called by :meth:`Flask.register_blueprint` to register all275 views and callbacks registered on the blueprint with the276 application. Creates a :class:`.BlueprintSetupState` and calls277 each :meth:`record` callback with it.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, # type: ignore[attr-defined]327 endpoint="static",328 )329330 # Merge blueprint data into parent.331 if first_bp_registration or first_name_registration:332 self._merge_blueprint_funcs(app, name)333334 for deferred in self.deferred_functions:335 deferred(state)336337 cli_resolved_group = options.get("cli_group", self.cli_group)338339 if self.cli.commands:340 if cli_resolved_group is None:341 app.cli.commands.update(self.cli.commands)342 elif cli_resolved_group is _sentinel:343 self.cli.name = name344 app.cli.add_command(self.cli)345 else:346 self.cli.name = cli_resolved_group347 app.cli.add_command(self.cli)348349 for blueprint, bp_options in self._blueprints:350 bp_options = bp_options.copy()351 bp_url_prefix = bp_options.get("url_prefix")352 bp_subdomain = bp_options.get("subdomain")353354 if bp_subdomain is None:355 bp_subdomain = blueprint.subdomain356357 if state.subdomain is not None and bp_subdomain is not None:358 bp_options["subdomain"] = bp_subdomain + "." + state.subdomain359 elif bp_subdomain is not None:360 bp_options["subdomain"] = bp_subdomain361 elif state.subdomain is not None:362 bp_options["subdomain"] = state.subdomain363364 if bp_url_prefix is None:365 bp_url_prefix = blueprint.url_prefix366367 if state.url_prefix is not None and bp_url_prefix is not None:368 bp_options["url_prefix"] = (369 state.url_prefix.rstrip("/") + "/" + bp_url_prefix.lstrip("/")370 )371 elif bp_url_prefix is not None:372 bp_options["url_prefix"] = bp_url_prefix373 elif state.url_prefix is not None:374 bp_options["url_prefix"] = state.url_prefix375376 bp_options["name_prefix"] = name377 blueprint.register(app, bp_options)378379 def _merge_blueprint_funcs(self, app: App, name: str) -> None:380 def extend(bp_dict, parent_dict):381 for key, values in bp_dict.items():382 key = name if key is None else f"{name}.{key}"383 parent_dict[key].extend(values)384385 for key, value in self.error_handler_spec.items():386 key = name if key is None else f"{name}.{key}"387 value = defaultdict(388 dict,389 {390 code: {exc_class: func for exc_class, func in code_values.items()}391 for code, code_values in value.items()392 },393 )394 app.error_handler_spec[key] = value395396 for endpoint, func in self.view_functions.items():397 app.view_functions[endpoint] = func398399 extend(self.before_request_funcs, app.before_request_funcs)400 extend(self.after_request_funcs, app.after_request_funcs)401 extend(402 self.teardown_request_funcs,403 app.teardown_request_funcs,404 )405 extend(self.url_default_functions, app.url_default_functions)406 extend(self.url_value_preprocessors, app.url_value_preprocessors)407 extend(self.template_context_processors, app.template_context_processors)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/README.md+6 added
added:src/flask/sansio/scaffold.py+802 added
1from __future__ import annotations23import importlib.util4import os5import pathlib6import sys7import typing as t8from collections import defaultdict9from functools import update_wrapper1011from jinja2 import FileSystemLoader12from werkzeug.exceptions import default_exceptions13from werkzeug.exceptions import HTTPException14from werkzeug.utils import cached_property1516from .. import typing as ft17from ..cli import AppGroup18from ..helpers import get_root_path19from ..templating import _default_template_ctx_processor2021# a singleton sentinel value for parameter defaults22_sentinel = object()2324F = t.TypeVar("F", bound=t.Callable[..., t.Any])25T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable)26T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable)27T_error_handler = t.TypeVar("T_error_handler", bound=ft.ErrorHandlerCallable)28T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)29T_template_context_processor = t.TypeVar(30 "T_template_context_processor", bound=ft.TemplateContextProcessorCallable31)32T_url_defaults = t.TypeVar("T_url_defaults", bound=ft.URLDefaultCallable)33T_url_value_preprocessor = t.TypeVar(34 "T_url_value_preprocessor", bound=ft.URLValuePreprocessorCallable35)36T_route = t.TypeVar("T_route", bound=ft.RouteCallable)373839def setupmethod(f: F) -> F:40 f_name = f.__name__4142 def wrapper_func(self, *args: t.Any, **kwargs: t.Any) -> t.Any:43 self._check_setup_finished(f_name)44 return f(self, *args, **kwargs)4546 return t.cast(F, update_wrapper(wrapper_func, f))474849class Scaffold:50 """Common behavior shared between :class:`~flask.Flask` and51 :class:`~flask.blueprints.Blueprint`.5253 :param import_name: The import name of the module where this object54 is defined. Usually :attr:`__name__` should be used.55 :param static_folder: Path to a folder of static files to serve.56 If this is set, a static route will be added.57 :param static_url_path: URL prefix for the static route.58 :param template_folder: Path to a folder containing template files.59 for rendering. If this is set, a Jinja loader will be added.60 :param root_path: The path that static, template, and resource files61 are relative to. Typically not set, it is discovered based on62 the ``import_name``.6364 .. versionadded:: 2.065 """6667 name: str68 _static_folder: str | None = None69 _static_url_path: str | None = None7071 def __init__(72 self,73 import_name: str,74 static_folder: str | os.PathLike | None = None,75 static_url_path: str | None = None,76 template_folder: str | os.PathLike | None = None,77 root_path: str | None = None,78 ):79 #: The name of the package or module that this object belongs80 #: to. Do not change this once it is set by the constructor.81 self.import_name = import_name8283 self.static_folder = static_folder # type: ignore84 self.static_url_path = static_url_path8586 #: The path to the templates folder, relative to87 #: :attr:`root_path`, to add to the template loader. ``None`` if88 #: templates should not be added.89 self.template_folder = template_folder9091 if root_path is None:92 root_path = get_root_path(self.import_name)9394 #: Absolute path to the package on the filesystem. Used to look95 #: up resources contained in the package.96 self.root_path = root_path9798 #: The Click command group for registering CLI commands for this99 #: object. The commands are available from the ``flask`` command100 #: once the application has been discovered and blueprints have101 #: been registered.102 self.cli = AppGroup()103104 #: A dictionary mapping endpoint names to view functions.105 #:106 #: To register a view function, use the :meth:`route` decorator.107 #:108 #: This data structure is internal. It should not be modified109 #: directly and its format may change at any time.110 self.view_functions: dict[str, t.Callable] = {}111112 #: A data structure of registered error handlers, in the format113 #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is114 #: the name of a blueprint the handlers are active for, or115 #: ``None`` for all requests. The ``code`` key is the HTTP116 #: status code for ``HTTPException``, or ``None`` for117 #: other exceptions. The innermost dictionary maps exception118 #: classes to handler functions.119 #:120 #: To register an error handler, use the :meth:`errorhandler`121 #: decorator.122 #:123 #: This data structure is internal. It should not be modified124 #: directly and its format may change at any time.125 self.error_handler_spec: dict[126 ft.AppOrBlueprintKey,127 dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]],128 ] = defaultdict(lambda: defaultdict(dict))129130 #: A data structure of functions to call at the beginning of131 #: each request, in the format ``{scope: [functions]}``. The132 #: ``scope`` key is the name of a blueprint the functions are133 #: active for, or ``None`` for all requests.134 #:135 #: To register a function, use the :meth:`before_request`136 #: decorator.137 #:138 #: This data structure is internal. It should not be modified139 #: directly and its format may change at any time.140 self.before_request_funcs: dict[141 ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]142 ] = defaultdict(list)143144 #: A data structure of functions to call at the end of each145 #: request, in the format ``{scope: [functions]}``. The146 #: ``scope`` key is the name of a blueprint the functions are147 #: active for, or ``None`` for all requests.148 #:149 #: To register a function, use the :meth:`after_request`150 #: decorator.151 #:152 #: This data structure is internal. It should not be modified153 #: directly and its format may change at any time.154 self.after_request_funcs: dict[155 ft.AppOrBlueprintKey, list[ft.AfterRequestCallable]156 ] = defaultdict(list)157158 #: A data structure of functions to call at the end of each159 #: request even if an exception is raised, in the format160 #: ``{scope: [functions]}``. The ``scope`` key is the name of a161 #: blueprint the functions are active for, or ``None`` for all162 #: requests.163 #:164 #: To register a function, use the :meth:`teardown_request`165 #: decorator.166 #:167 #: This data structure is internal. It should not be modified168 #: directly and its format may change at any time.169 self.teardown_request_funcs: dict[170 ft.AppOrBlueprintKey, list[ft.TeardownCallable]171 ] = defaultdict(list)172173 #: A data structure of functions to call to pass extra context174 #: values when rendering templates, in the format175 #: ``{scope: [functions]}``. The ``scope`` key is the name of a176 #: blueprint the functions are active for, or ``None`` for all177 #: requests.178 #:179 #: To register a function, use the :meth:`context_processor`180 #: decorator.181 #:182 #: This data structure is internal. It should not be modified183 #: directly and its format may change at any time.184 self.template_context_processors: dict[185 ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]186 ] = defaultdict(list, {None: [_default_template_ctx_processor]})187188 #: A data structure of functions to call to modify the keyword189 #: arguments passed to the view function, in the format190 #: ``{scope: [functions]}``. The ``scope`` key is the name of a191 #: blueprint the functions are active for, or ``None`` for all192 #: requests.193 #:194 #: To register a function, use the195 #: :meth:`url_value_preprocessor` decorator.196 #:197 #: This data structure is internal. It should not be modified198 #: directly and its format may change at any time.199 self.url_value_preprocessors: dict[200 ft.AppOrBlueprintKey,201 list[ft.URLValuePreprocessorCallable],202 ] = defaultdict(list)203204 #: A data structure of functions to call to modify the keyword205 #: arguments when generating URLs, in the format206 #: ``{scope: [functions]}``. The ``scope`` key is the name of a207 #: blueprint the functions are active for, or ``None`` for all208 #: requests.209 #:210 #: To register a function, use the :meth:`url_defaults`211 #: decorator.212 #:213 #: This data structure is internal. It should not be modified214 #: directly and its format may change at any time.215 self.url_default_functions: dict[216 ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]217 ] = defaultdict(list)218219 def __repr__(self) -> str:220 return f"<{type(self).__name__} {self.name!r}>"221222 def _check_setup_finished(self, f_name: str) -> None:223 raise NotImplementedError224225 @property226 def static_folder(self) -> str | None:227 """The absolute path to the configured static folder. ``None``228 if no static folder is set.229 """230 if self._static_folder is not None:231 return os.path.join(self.root_path, self._static_folder)232 else:233 return None234235 @static_folder.setter236 def static_folder(self, value: str | os.PathLike | None) -> None:237 if value is not None:238 value = os.fspath(value).rstrip(r"\/")239240 self._static_folder = value241242 @property243 def has_static_folder(self) -> bool:244 """``True`` if :attr:`static_folder` is set.245246 .. versionadded:: 0.5247 """248 return self.static_folder is not None249250 @property251 def static_url_path(self) -> str | None:252 """The URL prefix that the static route will be accessible from.253254 If it was not configured during init, it is derived from255 :attr:`static_folder`.256 """257 if self._static_url_path is not None:258 return self._static_url_path259260 if self.static_folder is not None:261 basename = os.path.basename(self.static_folder)262 return f"/{basename}".rstrip("/")263264 return None265266 @static_url_path.setter267 def static_url_path(self, value: str | None) -> None:268 if value is not None:269 value = value.rstrip("/")270271 self._static_url_path = value272273 @cached_property274 def jinja_loader(self) -> FileSystemLoader | None:275 """The Jinja loader for this object's templates. By default this276 is a class :class:`jinja2.loaders.FileSystemLoader` to277 :attr:`template_folder` if it is set.278279 .. versionadded:: 0.5280 """281 if self.template_folder is not None:282 return FileSystemLoader(os.path.join(self.root_path, self.template_folder))283 else:284 return None285286 def _method_route(287 self,288 method: str,289 rule: str,290 options: dict,291 ) -> t.Callable[[T_route], T_route]:292 if "methods" in options:293 raise TypeError("Use the 'route' decorator to use the 'methods' argument.")294295 return self.route(rule, methods=[method], **options)296297 @setupmethod298 def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:299 """Shortcut for :meth:`route` with ``methods=["GET"]``.300301 .. versionadded:: 2.0302 """303 return self._method_route("GET", rule, options)304305 @setupmethod306 def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:307 """Shortcut for :meth:`route` with ``methods=["POST"]``.308309 .. versionadded:: 2.0310 """311 return self._method_route("POST", rule, options)312313 @setupmethod314 def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:315 """Shortcut for :meth:`route` with ``methods=["PUT"]``.316317 .. versionadded:: 2.0318 """319 return self._method_route("PUT", rule, options)320321 @setupmethod322 def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:323 """Shortcut for :meth:`route` with ``methods=["DELETE"]``.324325 .. versionadded:: 2.0326 """327 return self._method_route("DELETE", rule, options)328329 @setupmethod330 def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:331 """Shortcut for :meth:`route` with ``methods=["PATCH"]``.332333 .. versionadded:: 2.0334 """335 return self._method_route("PATCH", rule, options)336337 @setupmethod338 def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:339 """Decorate a view function to register it with the given URL340 rule and options. Calls :meth:`add_url_rule`, which has more341 details about the implementation.342343 .. code-block:: python344345 @app.route("/")346 def index():347 return "Hello, World!"348349 See :ref:`url-route-registrations`.350351 The endpoint name for the route defaults to the name of the view352 function if the ``endpoint`` parameter isn't passed.353354 The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and355 ``OPTIONS`` are added automatically.356357 :param rule: The URL rule string.358 :param options: Extra options passed to the359 :class:`~werkzeug.routing.Rule` object.360 """361362 def decorator(f: T_route) -> T_route:363 endpoint = options.pop("endpoint", None)364 self.add_url_rule(rule, endpoint, f, **options)365 return f366367 return decorator368369 @setupmethod370 def add_url_rule(371 self,372 rule: str,373 endpoint: str | None = None,374 view_func: ft.RouteCallable | None = None,375 provide_automatic_options: bool | None = None,376 **options: t.Any,377 ) -> None:378 """Register a rule for routing incoming requests and building379 URLs. The :meth:`route` decorator is a shortcut to call this380 with the ``view_func`` argument. These are equivalent:381382 .. code-block:: python383384 @app.route("/")385 def index():386 ...387388 .. code-block:: python389390 def index():391 ...392393 app.add_url_rule("/", view_func=index)394395 See :ref:`url-route-registrations`.396397 The endpoint name for the route defaults to the name of the view398 function if the ``endpoint`` parameter isn't passed. An error399 will be raised if a function has already been registered for the400 endpoint.401402 The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` is403 always added automatically, and ``OPTIONS`` is added404 automatically by default.405406 ``view_func`` does not necessarily need to be passed, but if the407 rule should participate in routing an endpoint name must be408 associated with a view function at some point with the409 :meth:`endpoint` decorator.410411 .. code-block:: python412413 app.add_url_rule("/", endpoint="index")414415 @app.endpoint("index")416 def index():417 ...418419 If ``view_func`` has a ``required_methods`` attribute, those420 methods are added to the passed and automatic methods. If it421 has a ``provide_automatic_methods`` attribute, it is used as the422 default if the parameter is not passed.423424 :param rule: The URL rule string.425 :param endpoint: The endpoint name to associate with the rule426 and view function. Used when routing and building URLs.427 Defaults to ``view_func.__name__``.428 :param view_func: The view function to associate with the429 endpoint name.430 :param provide_automatic_options: Add the ``OPTIONS`` method and431 respond to ``OPTIONS`` requests automatically.432 :param options: Extra options passed to the433 :class:`~werkzeug.routing.Rule` object.434 """435 raise NotImplementedError436437 @setupmethod438 def endpoint(self, endpoint: str) -> t.Callable[[F], F]:439 """Decorate a view function to register it for the given440 endpoint. Used if a rule is added without a ``view_func`` with441 :meth:`add_url_rule`.442443 .. code-block:: python444445 app.add_url_rule("/ex", endpoint="example")446447 @app.endpoint("example")448 def example():449 ...450451 :param endpoint: The endpoint name to associate with the view452 function.453 """454455 def decorator(f: F) -> F:456 self.view_functions[endpoint] = f457 return f458459 return decorator460461 @setupmethod462 def before_request(self, f: T_before_request) -> T_before_request:463 """Register a function to run before each request.464465 For example, this can be used to open a database connection, or466 to load the logged in user from the session.467468 .. code-block:: python469470 @app.before_request471 def load_user():472 if "user_id" in session:473 g.user = db.session.get(session["user_id"])474475 The function will be called without any arguments. If it returns476 a non-``None`` value, the value is handled as if it was the477 return value from the view, and further request handling is478 stopped.479480 This is available on both app and blueprint objects. When used on an app, this481 executes before every request. When used on a blueprint, this executes before482 every request that the blueprint handles. To register with a blueprint and483 execute before every request, use :meth:`.Blueprint.before_app_request`.484 """485 self.before_request_funcs.setdefault(None, []).append(f)486 return f487488 @setupmethod489 def after_request(self, f: T_after_request) -> T_after_request:490 """Register a function to run after each request to this object.491492 The function is called with the response object, and must return493 a response object. This allows the functions to modify or494 replace the response before it is sent.495496 If a function raises an exception, any remaining497 ``after_request`` functions will not be called. Therefore, this498 should not be used for actions that must execute, such as to499 close resources. Use :meth:`teardown_request` for that.500501 This is available on both app and blueprint objects. When used on an app, this502 executes after every request. When used on a blueprint, this executes after503 every request that the blueprint handles. To register with a blueprint and504 execute after every request, use :meth:`.Blueprint.after_app_request`.505 """506 self.after_request_funcs.setdefault(None, []).append(f)507 return f508509 @setupmethod510 def teardown_request(self, f: T_teardown) -> T_teardown:511 """Register a function to be called when the request context is512 popped. Typically this happens at the end of each request, but513 contexts may be pushed manually as well during testing.514515 .. code-block:: python516517 with app.test_request_context():518 ...519520 When the ``with`` block exits (or ``ctx.pop()`` is called), the521 teardown functions are called just before the request context is522 made inactive.523524 When a teardown function was called because of an unhandled525 exception it will be passed an error object. If an526 :meth:`errorhandler` is registered, it will handle the exception527 and the teardown will not receive it.528529 Teardown functions must avoid raising exceptions. If they530 execute code that might fail they must surround that code with a531 ``try``/``except`` block and log any errors.532533 The return values of teardown functions are ignored.534535 This is available on both app and blueprint objects. When used on an app, this536 executes after every request. When used on a blueprint, this executes after537 every request that the blueprint handles. To register with a blueprint and538 execute after every request, use :meth:`.Blueprint.teardown_app_request`.539 """540 self.teardown_request_funcs.setdefault(None, []).append(f)541 return f542543 @setupmethod544 def context_processor(545 self,546 f: T_template_context_processor,547 ) -> T_template_context_processor:548 """Registers a template context processor function. These functions run before549 rendering a template. The keys of the returned dict are added as variables550 available in the template.551552 This is available on both app and blueprint objects. When used on an app, this553 is called for every rendered template. When used on a blueprint, this is called554 for templates rendered from the blueprint's views. To register with a blueprint555 and affect every template, use :meth:`.Blueprint.app_context_processor`.556 """557 self.template_context_processors[None].append(f)558 return f559560 @setupmethod561 def url_value_preprocessor(562 self,563 f: T_url_value_preprocessor,564 ) -> T_url_value_preprocessor:565 """Register a URL value preprocessor function for all view566 functions in the application. These functions will be called before the567 :meth:`before_request` functions.568569 The function can modify the values captured from the matched url before570 they are passed to the view. For example, this can be used to pop a571 common language code value and place it in ``g`` rather than pass it to572 every view.573574 The function is passed the endpoint name and values dict. The return575 value is ignored.576577 This is available on both app and blueprint objects. When used on an app, this578 is called for every request. When used on a blueprint, this is called for579 requests that the blueprint handles. To register with a blueprint and affect580 every request, use :meth:`.Blueprint.app_url_value_preprocessor`.581 """582 self.url_value_preprocessors[None].append(f)583 return f584585 @setupmethod586 def url_defaults(self, f: T_url_defaults) -> T_url_defaults:587 """Callback function for URL defaults for all view functions of the588 application. It's called with the endpoint and values and should589 update the values passed in place.590591 This is available on both app and blueprint objects. When used on an app, this592 is called for every request. When used on a blueprint, this is called for593 requests that the blueprint handles. To register with a blueprint and affect594 every request, use :meth:`.Blueprint.app_url_defaults`.595 """596 self.url_default_functions[None].append(f)597 return f598599 @setupmethod600 def errorhandler(601 self, code_or_exception: type[Exception] | int602 ) -> t.Callable[[T_error_handler], T_error_handler]:603 """Register a function to handle errors by code or exception class.604605 A decorator that is used to register a function given an606 error code. Example::607608 @app.errorhandler(404)609 def page_not_found(error):610 return 'This page does not exist', 404611612 You can also register handlers for arbitrary exceptions::613614 @app.errorhandler(DatabaseError)615 def special_exception_handler(error):616 return 'Database connection failed', 500617618 This is available on both app and blueprint objects. When used on an app, this619 can handle errors from every request. When used on a blueprint, this can handle620 errors from requests that the blueprint handles. To register with a blueprint621 and affect every request, use :meth:`.Blueprint.app_errorhandler`.622623 .. versionadded:: 0.7624 Use :meth:`register_error_handler` instead of modifying625 :attr:`error_handler_spec` directly, for application wide error626 handlers.627628 .. versionadded:: 0.7629 One can now additionally also register custom exception types630 that do not necessarily have to be a subclass of the631 :class:`~werkzeug.exceptions.HTTPException` class.632633 :param code_or_exception: the code as integer for the handler, or634 an arbitrary exception635 """636637 def decorator(f: T_error_handler) -> T_error_handler:638 self.register_error_handler(code_or_exception, f)639 return f640641 return decorator642643 @setupmethod644 def register_error_handler(645 self,646 code_or_exception: type[Exception] | int,647 f: ft.ErrorHandlerCallable,648 ) -> None:649 """Alternative error attach function to the :meth:`errorhandler`650 decorator that is more straightforward to use for non decorator651 usage.652653 .. versionadded:: 0.7654 """655 exc_class, code = self._get_exc_class_and_code(code_or_exception)656 self.error_handler_spec[None][code][exc_class] = f657658 @staticmethod659 def _get_exc_class_and_code(660 exc_class_or_code: type[Exception] | int,661 ) -> tuple[type[Exception], int | None]:662 """Get the exception class being handled. For HTTP status codes663 or ``HTTPException`` subclasses, return both the exception and664 status code.665666 :param exc_class_or_code: Any exception class, or an HTTP status667 code as an integer.668 """669 exc_class: type[Exception]670671 if isinstance(exc_class_or_code, int):672 try:673 exc_class = default_exceptions[exc_class_or_code]674 except KeyError:675 raise ValueError(676 f"'{exc_class_or_code}' is not a recognized HTTP"677 " error code. Use a subclass of HTTPException with"678 " that code instead."679 ) from None680 else:681 exc_class = exc_class_or_code682683 if isinstance(exc_class, Exception):684 raise TypeError(685 f"{exc_class!r} is an instance, not a class. Handlers"686 " can only be registered for Exception classes or HTTP"687 " error codes."688 )689690 if not issubclass(exc_class, Exception):691 raise ValueError(692 f"'{exc_class.__name__}' is not a subclass of Exception."693 " Handlers can only be registered for Exception classes"694 " or HTTP error codes."695 )696697 if issubclass(exc_class, HTTPException):698 return exc_class, exc_class.code699 else:700 return exc_class, None701702703def _endpoint_from_view_func(view_func: t.Callable) -> str:704 """Internal helper that returns the default endpoint for a given705 function. This always is the function name.706 """707 assert view_func is not None, "expected view func if endpoint is not provided."708 return view_func.__name__709710711def _path_is_relative_to(path: pathlib.PurePath, base: str) -> bool:712 # Path.is_relative_to doesn't exist until Python 3.9713 try:714 path.relative_to(base)715 return True716 except ValueError:717 return False718719720def _find_package_path(import_name):721 """Find the path that contains the package or module."""722 root_mod_name, _, _ = import_name.partition(".")723724 try:725 root_spec = importlib.util.find_spec(root_mod_name)726727 if root_spec is None:728 raise ValueError("not found")729 except (ImportError, ValueError):730 # ImportError: the machinery told us it does not exist731 # ValueError:732 # - the module name was invalid733 # - the module name is __main__734 # - we raised `ValueError` due to `root_spec` being `None`735 return os.getcwd()736737 if root_spec.origin in {"namespace", None}:738 # namespace package739 package_spec = importlib.util.find_spec(import_name)740741 if package_spec is not None and package_spec.submodule_search_locations:742 # Pick the path in the namespace that contains the submodule.743 package_path = pathlib.Path(744 os.path.commonpath(package_spec.submodule_search_locations)745 )746 search_location = next(747 location748 for location in root_spec.submodule_search_locations749 if _path_is_relative_to(package_path, location)750 )751 else:752 # Pick the first path.753 search_location = root_spec.submodule_search_locations[0]754755 return os.path.dirname(search_location)756 elif root_spec.submodule_search_locations:757 # package with __init__.py758 return os.path.dirname(os.path.dirname(root_spec.origin))759 else:760 # module761 return os.path.dirname(root_spec.origin)762763764def find_package(import_name: str):765 """Find the prefix that a package is installed under, and the path766 that it would be imported from.767768 The prefix is the directory containing the standard directory769 hierarchy (lib, bin, etc.). If the package is not installed to the770 system (:attr:`sys.prefix`) or a virtualenv (``site-packages``),771 ``None`` is returned.772773 The path is the entry in :attr:`sys.path` that contains the package774 for import. If the package is not installed, it's assumed that the775 package was imported from the current working directory.776 """777 package_path = _find_package_path(import_name)778 py_prefix = os.path.abspath(sys.prefix)779780 # installed to the system781 if _path_is_relative_to(pathlib.PurePath(package_path), py_prefix):782 return py_prefix, package_path783784 site_parent, site_folder = os.path.split(package_path)785786 # installed to a virtualenv787 if site_folder.lower() == "site-packages":788 parent, folder = os.path.split(site_parent)789790 # Windows (prefix/lib/site-packages)791 if folder.lower() == "lib":792 return parent, package_path793794 # Unix (prefix/lib/pythonX.Y/site-packages)795 if os.path.basename(parent).lower() == "lib":796 return os.path.dirname(parent), package_path797798 # something else (prefix/site-packages)799 return site_parent, package_path800801 # not installed802 return None, package_path
modified:src/flask/__init__.py+2 added-2 removed
1from . import json as json2from .app import Flask as Flask3from .app import Request as Request4from .app import Response as Response3from .blueprints import Blueprint as Blueprint4from .config import Config as Config5from .ctx import after_this_request as after_this_request6from .ctx import copy_current_request_context as copy_current_request_context
27 unmodified lines
34from .templating import render_template as render_template35from .templating import render_template_string as render_template_string36from .templating import stream_template as stream_template37from .templating import stream_template_string as stream_template_string38from .wrappers import Request as Request39from .wrappers import Response as Response4041__version__ = "3.0.0.dev"
modified:src/flask/app.py+137 added-853 removed
1from __future__ import annotations23import logging3import os4import sys5import typing as t6import weakref
6 unmodified lines
1314import click15from werkzeug.datastructures import Headers16from werkzeug.datastructures import ImmutableDict18from werkzeug.exceptions import Aborter19from werkzeug.exceptions import BadRequest17from werkzeug.exceptions import BadRequestKeyError18from werkzeug.exceptions import HTTPException19from werkzeug.exceptions import InternalServerError20from werkzeug.routing import BuildError24from werkzeug.routing import Map21from werkzeug.routing import MapAdapter22from werkzeug.routing import RequestRedirect23from werkzeug.routing import RoutingException24from werkzeug.routing import Rule25from werkzeug.serving import is_running_from_reloader30from werkzeug.utils import cached_property31from werkzeug.utils import redirect as _wz_redirect26from werkzeug.wrappers import Response as BaseResponse2728from . import cli29from . import typing as ft36from .config import Config37from .config import ConfigAttribute38from .ctx import _AppCtxGlobals30from .ctx import AppContext31from .ctx import RequestContext32from .globals import _cv_app33from .globals import _cv_request34from .globals import current_app35from .globals import g36from .globals import request37from .globals import request_ctx38from .globals import session47from .helpers import _split_blueprint_path39from .helpers import get_debug_flag40from .helpers import get_flashed_messages41from .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 setupmethod42from .helpers import send_from_directory43from .sansio.app import App44from .sansio.scaffold import _sentinel45from .sessions import SecureCookieSessionInterface46from .sessions import SessionInterface47from .signals import appcontext_tearing_down48from .signals import got_request_exception49from .signals import request_finished50from .signals import request_started51from .signals import request_tearing_down66from .templating import DispatchingJinjaLoader52from .templating import Environment53from .wrappers import Request54from .wrappers import Response5556if t.TYPE_CHECKING: # pragma: no cover72 from .blueprints import Blueprint57 from .testing import FlaskClient58 from .testing import FlaskCliRunner5960T_shell_context_processor = t.TypeVar(
11 unmodified lines
7273 return timedelta(seconds=value)747592class Flask(Scaffold):76class Flask(App):77 """The flask object implements a WSGI application and acts as the central78 object. It is passed the name of the module or package of the79 application. Once it is created it will act as a central registry for80 the view functions, the URL rules, template configuration and much more.
88 unmodified lines
169 This should only be set manually when it can't be detected170 automatically, such as for namespace packages.171 """172189 #: 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.173 default_config = ImmutableDict(174 {175 "DEBUG": None,176 "TESTING": False,
20 unmodified lines
197 "MAX_COOKIE_SIZE": 4093,198 }199 )200322 #: The rule object to use for URL rules created. This is used by323 #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.324 #:325 #: .. versionadded:: 0.7326 url_rule_class = Rule201 #: The class that is used for request objects. See :class:`~flask.Request`202 #: for more information.203 request_class = Request204328 #: The map object to use for storing the URL rules and routing329 #: configuration parameters. Defaults to :class:`werkzeug.routing.Map`.330 #:331 #: .. versionadded:: 1.1.0332 url_map_class = Map205 #: The class that is used for response objects. See206 #: :class:`~flask.Response` for more information.207 response_class = Response208334 #: 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 = None347209 #: the session interface to use. By default an instance of210 #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.211 #:212 #: .. versionadded:: 0.8
13 unmodified lines
226 root_path: str | None = None,227 ):228 super().__init__(229 import_name=import_name,369 static_folder=static_folder,230 static_url_path=static_url_path,231 static_folder=static_folder,232 static_host=static_host,233 host_matching=host_matching,234 subdomain_matching=subdomain_matching,235 template_folder=template_folder,236 instance_path=instance_path,237 instance_relative_config=instance_relative_config,238 root_path=root_path,239 )240375 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 = False485241 # Add a static route using the provided static_url_path, static_host,242 # and static_folder if there is a configured static_folder.243 # Note we do this without checking if static_folder exists.244 # For one, it might be created while the server is running (e.g. during
11 unmodified lines
256 host=static_host,257 view_func=lambda **kw: self_ref().send_static_file(**kw), # type: ignore # noqa: B950258 )259505 # Set the name of the Click group in case someone wants to add506 # the app's commands to another CLI tool.507 self.cli.name = self.name260 def get_send_file_max_age(self, filename: str | None) -> int | None:261 """Used by :func:`send_file` to determine the ``max_age`` cache262 value for a given file path if it wasn't passed.263509 def _check_setup_finished(self, f_name: str) -> None:510 if self._got_first_request:511 raise AssertionError(512 f"The setup method '{f_name}' can no longer be called"513 " on the application. It has already handled its first"514 " request, any changes will not be applied"515 " consistently.\n"516 "Make sure all imports, decorators, functions, etc."517 " needed to set up the application are done before"518 " running it."519 )264 By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from265 the configuration of :data:`~flask.current_app`. This defaults266 to ``None``, which tells the browser to use conditional requests267 instead of a timed cache, which is usually preferable.268521 @cached_property522 def name(self) -> str: # type: ignore523 """The name of the application. This is usually the import name524 with the difference that it's guessed from the run file if the525 import name is main. This name is used as a display name when526 Flask needs the name of the application. It can be set and overridden527 to change the value.269 Note this is a duplicate of the same method in the Flask270 class.271272 .. versionchanged:: 2.0273 The default configuration is ``None`` instead of 12 hours.274529 .. versionadded:: 0.8275 .. versionadded:: 0.9276 """531 if self.import_name == "__main__":532 fn = getattr(sys.modules["__main__"], "__file__", None)533 if fn is None:534 return "__main__"535 return os.path.splitext(os.path.basename(fn))[0]536 return self.import_name277 value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]278538 @cached_property539 def logger(self) -> logging.Logger:540 """A standard Python :class:`~logging.Logger` for the app, with541 the same name as :attr:`name`.279 if value is None:280 return None281543 In debug mode, the logger's :attr:`~logging.Logger.level` will544 be set to :data:`~logging.DEBUG`.282 if isinstance(value, timedelta):283 return int(value.total_seconds())284546 If there are no handlers configured, a default handler will be547 added. See :doc:`/logging` for more information.285 return value286549 .. versionchanged:: 1.1.0550 The logger takes the same name as :attr:`name` rather than551 hard-coding ``"flask.app"``.287 def send_static_file(self, filename: str) -> Response:288 """The view function used to serve files from289 :attr:`static_folder`. A route is automatically registered for290 this view at :attr:`static_url_path` if :attr:`static_folder` is291 set.292553 .. versionchanged:: 1.0.0554 Behavior was simplified. The logger is always named555 ``"flask.app"``. The level is only set during configuration,556 it doesn't check ``app.debug`` each time. Only one format is557 used, not different ones depending on ``app.debug``. No558 handlers are removed, and a handler is only added if no559 handlers are already configured.293 Note this is a duplicate of the same method in the Flask294 class.295561 .. versionadded:: 0.3562 """563 return create_logger(self)296 .. versionadded:: 0.5297565 @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.298 """573 return self.create_jinja_environment()299 if not self.has_static_folder:300 raise RuntimeError("'static_folder' must be set to serve static_files.")301575 def make_config(self, instance_relative: bool = False) -> Config:576 """Used to create the config attribute by the Flask constructor.577 The `instance_relative` parameter is passed in from the constructor578 of Flask (there named `instance_relative_config`) and indicates if579 the config should be relative to the instance path or the root path580 of the application.302 # send_file only knows to call get_send_file_max_age on the app,303 # call it here so it works for blueprints too.304 max_age = self.get_send_file_max_age(filename)305 return send_from_directory(306 t.cast(str, self.static_folder), filename, max_age=max_age307 )308582 .. versionadded:: 0.8583 """584 root_path = self.root_path585 if instance_relative:586 root_path = self.instance_path587 defaults = dict(self.default_config)588 defaults["DEBUG"] = get_debug_flag()589 return self.config_class(root_path, defaults)309 def open_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:310 """Open a resource file relative to :attr:`root_path` for311 reading.312591 def make_aborter(self) -> Aborter:592 """Create the object to assign to :attr:`aborter`. That object593 is called by :func:`flask.abort` to raise HTTP errors, and can594 be called directly as well.313 For example, if the file ``schema.sql`` is next to the file314 ``app.py`` where the ``Flask`` app is defined, it can be opened315 with:316596 By default, this creates an instance of :attr:`aborter_class`,597 which defaults to :class:`werkzeug.exceptions.Aborter`.317 .. code-block:: python318599 .. versionadded:: 2.2600 """601 return self.aborter_class()319 with app.open_resource("schema.sql") as f:320 conn.executescript(f.read())321603 def auto_find_instance_path(self) -> str:604 """Tries to locate the instance path if it was not provided to the605 constructor of the application class. It will basically calculate606 the path to a folder named ``instance`` next to your main file or607 the package.322 :param resource: Path to the resource relative to323 :attr:`root_path`.324 :param mode: Open the file in this mode. Only reading is325 supported, valid values are "r" (or "rt") and "rb".326609 .. versionadded:: 0.8327 Note this is a duplicate of the same method in the Flask328 class.329330 """611 prefix, package_path = find_package(self.import_name)612 if prefix is None:613 return os.path.join(package_path, "instance")614 return os.path.join(prefix, "var", f"{self.name}-instance")331 if mode not in {"r", "rt", "rb"}:332 raise ValueError("Resources can only be opened for reading.")333334 return open(os.path.join(self.root_path, resource), mode)335336 def open_instance_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:337 """Opens a resource from the application's instance folder338 (:attr:`instance_path`). Otherwise works like339 :meth:`open_resource`. Instance resources can also be opened for
44 unmodified lines
384 )385 rv.policies["json.dumps_function"] = self.json.dumps386 return rv387668 def create_global_jinja_loader(self) -> DispatchingJinjaLoader:669 """Creates the loader for the Jinja2 environment. Can be used to670 override just the loader and keeping the rest unchanged. It's671 discouraged to override this function. Instead one should override672 the :meth:`jinja_loader` function instead.388 def create_url_adapter(self, request: Request | None) -> MapAdapter | None:389 """Creates a URL adapter for the given request. The URL adapter390 is created at a point where the request context is not yet set391 up so the request is passed explicitly.392674 The global loader dispatches between the loaders of the application675 and the individual blueprints.393 .. versionadded:: 0.6394677 .. versionadded:: 0.7395 .. versionchanged:: 0.9396 This can now also be called without a request object when the397 URL adapter is created for the application context.398399 .. versionchanged:: 1.0400 :data:`SERVER_NAME` no longer implicitly enables subdomain401 matching. Use :attr:`subdomain_matching` instead.402 """679 return DispatchingJinjaLoader(self)403 if request is not None:404 # If subdomain matching is disabled (the default), use the405 # default subdomain in all cases. This should be the default406 # in Werkzeug but it currently does not have that feature.407 if not self.subdomain_matching:408 subdomain = self.url_map.default_subdomain or None409 else:410 subdomain = None411681 def select_jinja_autoescape(self, filename: str) -> bool:682 """Returns ``True`` if autoescaping should be active for the given683 template name. If no template name is given, returns `True`.412 print(self.config["SERVER_NAME"], subdomain)413 return self.url_map.bind_to_environ(414 request.environ,415 server_name=self.config["SERVER_NAME"],416 subdomain=subdomain,417 )418 # We need at the very least the server name to be set for this419 # to work.420 if self.config["SERVER_NAME"] is not None:421 return self.url_map.bind(422 self.config["SERVER_NAME"],423 script_name=self.config["APPLICATION_ROOT"],424 url_scheme=self.config["PREFERRED_URL_SCHEME"],425 )426685 .. versionchanged:: 2.2686 Autoescaping is now enabled by default for ``.svg`` files.427 return None428688 .. versionadded:: 0.5429 def raise_routing_exception(self, request: Request) -> t.NoReturn:430 """Intercept routing exceptions and possibly do something else.431432 In debug mode, intercept a routing redirect and replace it with433 an error if the body will be discarded.434435 With modern Werkzeug this shouldn't occur, since it now uses a436 308 status which tells the browser to resend the method and437 body.438439 .. versionchanged:: 2.1440 Don't intercept 307 and 308 redirects.441442 :meta private:443 :internal:444 """690 if filename is None:691 return True692 return filename.endswith((".html", ".htm", ".xml", ".xhtml", ".svg"))445 if (446 not self.debug447 or not isinstance(request.routing_exception, RequestRedirect)448 or request.routing_exception.code in {307, 308}449 or request.method in {"GET", "HEAD", "OPTIONS"}450 ):451 raise request.routing_exception # type: ignore452453 from .debughelpers import FormDataRoutingRedirect454455 raise FormDataRoutingRedirect(request)456457 def update_template_context(self, context: dict) -> None:458 """Update the template context with some commonly used variables.459 This injects request, session, config and g into the template460 context as well as everything template context processors want
16 unmodified lines
477478 for name in names:479 if name in self.template_context_processors:480 for func in self.template_context_processors[name]:718 context.update(func())481 context.update(self.ensure_sync(func)())482483 context.update(orig_ctx)484485 def make_shell_context(self) -> dict:
7 unmodified lines
493 for processor in self.shell_context_processors:494 rv.update(processor())495 return rv496734 @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 = value753497 def run(498 self,499 host: str | None = None,500 port: int | None = None,
190 unmodified lines
691 from .testing import FlaskCliRunner as cls692693 return cls(self, **kwargs) # type: ignore694952 @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 None1228695 def handle_http_exception(696 self, e: HTTPException697 ) -> HTTPException | ft.ResponseReturnValue:698 """Handles an HTTP exception. By default this will invoke the
22 unmodified lines
721 # are not raised or handled in user code.722 if isinstance(e, RoutingException):723 return e7241259 handler = self._find_error_handler(e)725 handler = self._find_error_handler(e, request.blueprints)726 if handler is None:727 return e728 return self.ensure_sync(handler)(e)7291264 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 False1298730 def handle_user_exception(731 self, e: Exception732 ) -> HTTPException | ft.ResponseReturnValue:733 """This method is called whenever an exception occurs that
17 unmodified lines
751752 if isinstance(e, HTTPException) and not self.trap_http_exception(e):753 return self.handle_http_exception(e)7541324 handler = self._find_error_handler(e)755 handler = self._find_error_handler(e, request.blueprints)756757 if handler is None:758 raise759
44 unmodified lines
804805 self.log_exception(exc_info)806 server_error: InternalServerError | ft.ResponseReturnValue807 server_error = InternalServerError(original_exception=e)1377 handler = self._find_error_handler(server_error)808 handler = self._find_error_handler(server_error, request.blueprints)809810 if handler is not None:811 server_error = self.ensure_sync(handler)(server_error)812
13 unmodified lines
826 self.logger.error(827 f"Exception on {request.path} [{request.method}]", exc_info=exc_info828 )8291399 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)1426830 def dispatch_request(self) -> ft.ResponseReturnValue:831 """Does the request dispatching. Matches the URL and returns the832 return value of the view or error handler. This does not have to833 be a response object. In order to convert the return value to a
79 unmodified lines
913 rv = self.response_class()914 rv.allow.update(methods)915 return rv9161514 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 False1523917 def ensure_sync(self, func: t.Callable) -> t.Callable:918 """Ensure that the function is synchronous for WSGI workers.919 Plain ``def`` functions are returned as-is. ``async def``920 functions are wrapped to run and wait for the response.
154 unmodified lines
1075 rv = f"{rv}#{_anchor}"10761077 return rv10781686 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)16991079 def make_response(self, rv: ft.ResponseReturnValue) -> Response:1080 """Convert the return value from a view function to an instance of1081 :attr:`response_class`.1082
132 unmodified lines
1215 rv.headers.update(headers) # type: ignore[arg-type]12161217 return rv12181840 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 error19341219 def preprocess_request(self) -> ft.ResponseReturnValue | None:1220 """Called before the request is dispatched. Calls1221 :attr:`url_value_preprocessors` registered with the app and the1222 current blueprint (if any). Then calls :attr:`before_request_funcs`
256 unmodified lines
modified:src/flask/blueprints.py+58 added-593 removed
1from __future__ import annotations23import os4import typing as t5from collections import defaultdict6from functools import update_wrapper5from datetime import timedelta68from . import typing as ft9from .scaffold import _endpoint_from_view_func10from .scaffold import _sentinel11from .scaffold import Scaffold12from .scaffold import setupmethod7from .globals import current_app8from .helpers import send_from_directory9from .sansio.blueprints import Blueprint as SansioBlueprint10from .sansio.blueprints import BlueprintSetupState as BlueprintSetupState # noqa1112if t.TYPE_CHECKING: # pragma: no cover15 from .app import Flask13 from .wrappers import Response1417DeferredSetupFunction = 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)1516class Blueprint(SansioBlueprint):17 def get_send_file_max_age(self, filename: str | None) -> int | None:18 """Used by :func:`send_file` to determine the ``max_age`` cache19 value for a given file path if it wasn't passed.2034class BlueprintSetupState:35 """Temporary holder object for registering a blueprint with the36 application. An instance of this class is created by the37 :meth:`~flask.Blueprint.make_setup_state` method and later passed38 to all register callback functions.39 """21 By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from22 the configuration of :data:`~flask.current_app`. This defaults23 to ``None``, which tells the browser to use conditional requests24 instead of a timed cache, which is usually preferable.2541 def __init__(42 self,43 blueprint: Blueprint,44 app: Flask,45 options: t.Any,46 first_registration: bool,47 ) -> None:48 #: a reference to the current application49 self.app = app26 Note this is a duplicate of the same method in the Flask27 class.2851 #: a reference to the blueprint that created this setup state.52 self.blueprint = blueprint29 .. versionchanged:: 2.030 The default configuration is ``None`` instead of 12 hours.3154 #: 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.32 .. versionadded:: 0.933 """98 if self.url_prefix is not None:99 if rule:100 rule = "/".join((self.url_prefix.rstrip("/"), rule.lstrip("/")))101 else:102 rule = self.url_prefix103 options.setdefault("subdomain", self.subdomain)104 if endpoint is None:105 endpoint = _endpoint_from_view_func(view_func) # type: ignore106 defaults = self.url_defaults107 if "defaults" in options:108 defaults = dict(defaults, **options.pop("defaults"))34 value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]35110 self.app.add_url_rule(111 rule,112 f"{self.name_prefix}.{self.name}.{endpoint}".lstrip("."),113 view_func,114 defaults=defaults,115 **options,116 )36 if value is None:37 return None3839 if isinstance(value, timedelta):40 return int(value.total_seconds())41119class Blueprint(Scaffold):120 """Represents a blueprint, a collection of routes and other121 app-related functions that can be registered on a real application122 later.42 return value43124 A blueprint is an object that allows defining application functions125 without requiring an application object ahead of time. It uses the126 same decorators as :class:`~flask.Flask`, but defers the need for an127 application by recording them for later registration.44 def send_static_file(self, filename: str) -> Response:45 """The view function used to serve files from46 :attr:`static_folder`. A route is automatically registered for47 this view at :attr:`static_url_path` if :attr:`static_folder` is48 set.49129 Decorating a function with a blueprint creates a deferred function130 that is called with :class:`~flask.blueprints.BlueprintSetupState`131 when the blueprint is registered on an application.50 Note this is a duplicate of the same method in the Flask51 class.52133 See :doc:`/blueprints` for more information.53 .. versionadded:: 0.554135 :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.55 """230 self.deferred_functions.append(func)56 if not self.has_static_folder:57 raise RuntimeError("'static_folder' must be set to serve static_files.")58232 @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 )59 # send_file only knows to call get_send_file_max_age on the app,60 # call it here so it works for blueprints too.61 max_age = self.get_send_file_max_age(filename)62 return send_from_directory(63 t.cast(str, self.static_folder), filename, max_age=max_age64 )65440 @setupmethod441 def app_template_filter(442 self, name: str | None = None443 ) -> t.Callable[[T_template_filter], T_template_filter]:444 """Register a template filter, available in any template rendered by the445 application. Equivalent to :meth:`.Flask.template_filter`.66 def open_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:67 """Open a resource file relative to :attr:`root_path` for68 reading.69447 :param name: the optional name of the filter, otherwise the448 function name will be used.449 """70 For example, if the file ``schema.sql`` is next to the file71 ``app.py`` where the ``Flask`` app is defined, it can be opened72 with:73451 def decorator(f: T_template_filter) -> T_template_filter:452 self.add_app_template_filter(f, name=name)453 return f74 .. code-block:: python75455 return decorator76 with app.open_resource("schema.sql") as f:77 conn.executescript(f.read())78457 @setupmethod458 def add_app_template_filter(459 self, f: ft.TemplateFilterCallable, name: str | None = None460 ) -> None:461 """Register a template filter, available in any template rendered by the462 application. Works like the :meth:`app_template_filter` decorator. Equivalent to463 :meth:`.Flask.add_template_filter`.79 :param resource: Path to the resource relative to80 :attr:`root_path`.81 :param mode: Open the file in this mode. Only reading is82 supported, valid values are "r" (or "rt") and "rb".83465 :param name: the optional name of the filter, otherwise the466 function name will be used.467 """84 Note this is a duplicate of the same method in the Flask85 class.86469 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.87 """88 if mode not in {"r", "rt", "rb"}:89 raise ValueError("Resources can only be opened for reading.")90487 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 f91 return open(os.path.join(self.root_path, resource), mode)
modified:src/flask/debughelpers.py+3 added-3 removed
1from __future__ import annotations23import typing as t45from .app import Flask5from .blueprints import Blueprint6from .globals import request_ctx7from .sansio.app import App8910class UnexpectedUnicodeError(AssertionError, UnicodeError):11 """Raised in places where we want some better error reporting for
100 unmodified lines
112 continue113 yield f"{key}: {value!r}"114115116def explain_template_loading_attempts(app: Flask, template, attempts) -> None:116def explain_template_loading_attempts(app: App, template, attempts) -> None:117 """This should help developers understand what failed"""118 info = [f"Locating template {template!r}:"]119 total_found = 0120 blueprint = None121 if request_ctx and request_ctx.request.blueprint is not None:122 blueprint = request_ctx.request.blueprint123124 for idx, (loader, srcobj, triple) in enumerate(attempts):125 if isinstance(srcobj, Flask):125 if isinstance(srcobj, App):126 src_info = f"application {srcobj.import_name!r}"127 elif isinstance(srcobj, Blueprint):128 src_info = f"blueprint {srcobj.name!r} ({srcobj.import_name})"129 else:
31 unmodified lines
modified:src/flask/logging.py+2 added-2 removed
7 unmodified lines
89from .globals import request1011if t.TYPE_CHECKING: # pragma: no cover12 from .app import Flask12 from .sansio.app import App131415@LocalProxy16def wsgi_errors_stream() -> t.TextIO:
34 unmodified lines
51 logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")52)535455def create_logger(app: Flask) -> logging.Logger:55def create_logger(app: App) -> logging.Logger:56 """Get the Flask app's logger and configure it if needed.5758 The logger name will be the same as59 :attr:`app.import_name <flask.Flask.name>`.
17 unmodified lines
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
modified:src/flask/templating.py+4 added-3 removed
15 unmodified lines
16from .signals import template_rendered1718if t.TYPE_CHECKING: # pragma: no cover19 from .app import Flask20 from .sansio.app import App20 from .scaffold import Scaffold21 from .sansio.scaffold import Scaffold222324def _default_template_ctx_processor() -> dict[str, t.Any]:25 """Default template context processor. Injects `request`,
15 unmodified lines
41 knowledge of how Flask's blueprint works so that it can prepend the42 name of the blueprint to referenced templates if necessary.43 """4444 def __init__(self, app: Flask, **options: t.Any) -> None:45 def __init__(self, app: App, **options: t.Any) -> None:46 if "loader" not in options:47 options["loader"] = app.create_global_jinja_loader()48 BaseEnvironment.__init__(self, **options)49 self.app = app
3 unmodified lines
53 """A loader that looks for templates in the application and all54 the blueprint folders.55 """5656 def __init__(self, app: Flask) -> None:57 def __init__(self, app: App) -> None:58 self.app = app5960 def get_source( # type: ignore61 self, environment: Environment, template: str
160 unmodified lines
modified:src/flask/typing.py+9 added-3 removed
3 unmodified lines
45if t.TYPE_CHECKING: # pragma: no cover6 from _typeshed.wsgi import WSGIApplication # noqa: F4017 from werkzeug.datastructures import Headers # noqa: F4018 from werkzeug.wrappers import Response # noqa: F4018 from werkzeug.sansio.response import Response # noqa: F401910# The possible types that are directly convertible or are a Response object.11ResponseValue = t.Union[12 "Response",
47 unmodified lines
60TeardownCallable = t.Union[61 t.Callable[[t.Optional[BaseException]], None],62 t.Callable[[t.Optional[BaseException]], t.Awaitable[None]],63]64TemplateContextProcessorCallable = t.Callable[[], t.Dict[str, t.Any]]64TemplateContextProcessorCallable = t.Union[65 t.Callable[[], t.Dict[str, t.Any]],66 t.Callable[[], t.Awaitable[t.Dict[str, t.Any]]],67]68TemplateFilterCallable = t.Callable[..., t.Any]69TemplateGlobalCallable = t.Callable[..., t.Any]70TemplateTestCallable = t.Callable[..., bool]71URLDefaultCallable = t.Callable[[str, dict], None]
4 unmodified lines
76# exceptions (and using a union type on the argument).77# https://github.com/pallets/flask/issues/409578# https://github.com/pallets/flask/issues/429579# https://github.com/pallets/flask/issues/429777ErrorHandlerCallable = t.Callable[[t.Any], ResponseReturnValue]80ErrorHandlerCallable = t.Union[81 t.Callable[[t.Any], ResponseReturnValue],82 t.Callable[[t.Any], t.Awaitable[ResponseReturnValue]],83]8485RouteCallable = t.Union[86 t.Callable[..., ResponseReturnValue],87 t.Callable[..., t.Awaitable[ResponseReturnValue]],
1 unmodified line
modified:CHANGES.rst+2 added
2 unmodified lines
34Unreleased56- Remove previously deprecated code. :pr:`5223`7- Restructure the code such that the Flask (app) and Blueprint8 classes have Sans-IO bases. :pr:`5127`91011Version 2.3.312-------------
1514 unmodified lines