Merge pull request #3933 from pallets/more-scaffold
Before adoption: this commit came in with the history the project adopted, so no landing records it.
more work on Scaffold base class
authored by David Lord · committed by GitHub · parents 3316604, 3dfc12e · Browse files · 4 files·+586 added−576 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+586 added−576 removed
- other:+586 added−576 removed
Provenance
- Commit
510c38c- Tree
ffe7404- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
3316604- Parent 2
3dfc12e
4 files changed+586 added−576 removed
modified:src/flask/app.py+4 added-79 removed
27 unmodified lines28 from .globals import _request_ctx_stack29 from .globals import g30 from .globals import request31 from .globals import session32-from .helpers import find_package32 from .helpers import get_debug_flag33 from .helpers import get_env34 from .helpers import get_flashed_messages35 from .helpers import get_load_dotenv2 unmodified lines38 from .json import jsonify39 from .logging import create_logger40 from .scaffold import _endpoint_from_view_func41 from .scaffold import _sentinel42+from .scaffold import find_package43 from .scaffold import Scaffold44 from .scaffold import setupmethod45 from .sessions import SecureCookieSessionInterface46 from .signals import appcontext_tearing_down298 unmodified lines345 #:346 #: .. versionadded:: 0.8347 session_interface = SecureCookieSessionInterface()348 349- # TODO remove the next three attrs when Sphinx :inherited-members: works350- # https://github.com/sphinx-doc/sphinx/issues/741351-352- #: The name of the package or module that this app belongs to. Do not353- #: change this once it is set by the constructor.354- import_name = None355-356- #: Location of the template files to be added to the template lookup.357- #: ``None`` if templates should not be added.358- template_folder = None359-360- #: Absolute path to the package on the filesystem. Used to look up361- #: resources contained in the package.362- root_path = None363-349 def __init__(350 self,351 import_name,352 static_url_path=None,648 unmodified lines1001 view_func=None,1002 provide_automatic_options=None,1003 **options,1004 ):1020- """Connects a URL rule. Works exactly like the :meth:`route`1021- decorator. If a view_func is provided it will be registered with the1022- endpoint.1023-1024- Basically this example::1025-1026- @app.route('/')1027- def index():1028- pass1029-1030- Is equivalent to the following::1031-1032- def index():1033- pass1034- app.add_url_rule('/', 'index', index)1035-1036- If the view_func is not provided you will need to connect the endpoint1037- to a view function like so::1038-1039- app.view_functions['index'] = index1040-1041- Internally :meth:`route` invokes :meth:`add_url_rule` so if you want1042- to customize the behavior via subclassing you only need to change1043- this method.1044-1045- For more information refer to :ref:`url-route-registrations`.1046-1047- .. versionchanged:: 0.21048- `view_func` parameter added.1049-1050- .. versionchanged:: 0.61051- ``OPTIONS`` is added automatically as method.1052-1053- :param rule: the URL rule as string1054- :param endpoint: the endpoint for the registered URL rule. Flask1055- itself assumes the name of the view function as1056- endpoint1057- :param view_func: the function to call when serving a request to the1058- provided endpoint1059- :param provide_automatic_options: controls whether the ``OPTIONS``1060- method should be added automatically. This can also be controlled1061- by setting the ``view_func.provide_automatic_options = False``1062- before adding the rule.1063- :param options: the options to be forwarded to the underlying1064- :class:`~werkzeug.routing.Rule` object. A change1065- to Werkzeug is handling of method options. methods1066- is a list of methods this rule should be limited1067- to (``GET``, ``POST`` etc.). By default a rule1068- just listens for ``GET`` (and implicitly ``HEAD``).1069- Starting with Flask 0.6, ``OPTIONS`` is implicitly1070- added and handled by the standard request handling.1071- """1005 if endpoint is None:1006 endpoint = _endpoint_from_view_func(view_func)1007 options["endpoint"] = endpoint1008 methods = options.pop("methods", None)340 unmodified lines1349 ``500``, it will be used. For consistency, the handler will1350 always receive the ``InternalServerError``. The original1351 unhandled exception is available as ``e.original_exception``.1352 1420- .. note::1421- Prior to Werkzeug 1.0.0, ``InternalServerError`` will not1422- always have an ``original_exception`` attribute. Use1423- ``getattr(e, "original_exception", None)`` to simulate the1424- behavior for compatibility.1425-1353 .. versionchanged:: 1.1.01354 Always passes the ``InternalServerError`` instance to the1355 handler, setting ``original_exception`` to the unhandled1356 error.592 unmodified lines1949 ctx.auto_pop(error)1950 1951 def __call__(self, environ, start_response):1952 """The WSGI server calls the Flask application object as the2026- WSGI application. This calls :meth:`wsgi_app` which can be2027- wrapped to applying middleware."""1953+ WSGI application. This calls :meth:`wsgi_app`, which can be1954+ wrapped to apply middleware.1955+ """1956 return self.wsgi_app(environ, start_response)2029-2030- def __repr__(self):2031- return f"<{type(self).__name__} {self.name!r}>"modified:src/flask/blueprints.py+46 added-66 removed
88 unmodified lines89 when the blueprint is registered on an application.90 91 See :doc:`/blueprints` for more information.92 93- .. versionchanged:: 1.1.094- Blueprints have a ``cli`` group to register nested CLI commands.95- The ``cli_group`` parameter controls the name of the group under96- the ``flask`` command.97-98- .. versionadded:: 0.799-93 :param name: The name of the blueprint. Will be prepended to each94 endpoint name.95 :param import_name: The name of the blueprint package, usually96 ``__name__``. This helps locate the ``root_path`` for the16 unmodified lines113 :param subdomain: A subdomain that blueprint routes will match on by114 default.115 :param url_defaults: A dict of default values that blueprint routes116 will receive by default.124- :param root_path: By default, the blueprint will automatically set this125- based on ``import_name``. In certain situations this automatic126- detection can fail, so the path can be specified manually127- instead.117+ :param root_path: By default, the blueprint will automatically set118+ this based on ``import_name``. In certain situations this119+ automatic detection can fail, so the path can be specified120+ manually instead.121+122+ .. versionchanged:: 1.1.0123+ Blueprints have a ``cli`` group to register nested CLI commands.124+ The ``cli_group`` parameter controls the name of the group under125+ the ``flask`` command.126+127+ .. versionadded:: 0.7128 """129 130 warn_on_modifications = False131 _got_registered_once = False132 133- #: Blueprint local JSON encoder class to use.134- #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_encoder`.133+ #: Blueprint local JSON encoder class to use. Set to ``None`` to use134+ #: the app's :class:`~flask.Flask.json_encoder`.135 json_encoder = None136- #: Blueprint local JSON decoder class to use.137- #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_decoder`.136+ #: Blueprint local JSON decoder class to use. Set to ``None`` to use137+ #: the app's :class:`~flask.Flask.json_decoder`.138 json_decoder = None139 140- # TODO remove the next three attrs when Sphinx :inherited-members: works141- # https://github.com/sphinx-doc/sphinx/issues/741142-143- #: The name of the package or module that this app belongs to. Do not144- #: change this once it is set by the constructor.145- import_name = None146-147- #: Location of the template files to be added to the template lookup.148- #: ``None`` if templates should not be added.149- template_folder = None150-151- #: Absolute path to the package on the filesystem. Used to look up152- #: resources contained in the package.153- root_path = None154-140 def __init__(141 self,142 name,143 import_name,16 unmodified lines160 self.name = name161 self.url_prefix = url_prefix162 self.subdomain = subdomain163 self.deferred_functions = []164+165 if url_defaults is None:166 url_defaults = {}167+168 self.url_values_defaults = url_defaults169 self.cli_group = cli_group170 171 def _is_setup_finished(self):9 unmodified lines181 from warnings import warn182 183 warn(184 Warning(198- "The blueprint was already registered once "199- "but is getting modified now. These changes "200- "will not show up."185+ "The blueprint was already registered once but is"186+ " getting modified now. These changes will not show"187+ " up."188 )189 )190 self.deferred_functions.append(func)191 17 unmodified lines209 """210 return BlueprintSetupState(self, app, options, first_registration)211 212 def register(self, app, options, first_registration=False):226- """Called by :meth:`Flask.register_blueprint` to register all views227- and callbacks registered on the blueprint with the application. Creates228- a :class:`.BlueprintSetupState` and calls each :meth:`record` callback229- with it.213+ """Called by :meth:`Flask.register_blueprint` to register all214+ views and callbacks registered on the blueprint with the215+ application. Creates a :class:`.BlueprintSetupState` and calls216+ each :meth:`record` callbackwith it.217 231- :param app: The application this blueprint is being registered with.218+ :param app: The application this blueprint is being registered219+ with.220 :param options: Keyword arguments forwarded from221 :meth:`~Flask.register_blueprint`.222 :param first_registration: Whether this is the first time this223 blueprint has been registered on the application.7 unmodified lines231 view_func=self.send_static_file,232 endpoint="static",233 )234 247- # Merge app and self dictionaries.248- def merge_dict_lists(self_dict, app_dict):249- """Merges self_dict into app_dict. Replaces None keys with self.name.250- Values of dict must be lists.251- """252- for key, values in self_dict.items():253- key = self.name if key is None else f"{self.name}.{key}"254- app_dict[key].extend(values)235+ # Merge blueprint data into parent.236+ if first_registration:237 256- def merge_dict_nested(self_dict, app_dict):257- """Merges self_dict into app_dict. Replaces None keys with self.name.258- Values of dict must be dict.259- """260- for key, value in self_dict.items():261- key = self.name if key is None else f"{self.name}.{key}"262- app_dict[key] = value238+ def extend(bp_dict, parent_dict):239+ for key, values in bp_dict.items():240+ key = self.name if key is None else f"{self.name}.{key}"241+ parent_dict[key].extend(values)242 264- app.view_functions.update(self.view_functions)243+ def update(bp_dict, parent_dict):244+ for key, value in bp_dict.items():245+ key = self.name if key is None else f"{self.name}.{key}"246+ parent_dict[key] = value247 266- merge_dict_lists(self.before_request_funcs, app.before_request_funcs)267- merge_dict_lists(self.after_request_funcs, app.after_request_funcs)268- merge_dict_lists(self.teardown_request_funcs, app.teardown_request_funcs)269- merge_dict_lists(self.url_default_functions, app.url_default_functions)270- merge_dict_lists(self.url_value_preprocessors, app.url_value_preprocessors)271- merge_dict_lists(272- self.template_context_processors, app.template_context_processors273- )248+ app.view_functions.update(self.view_functions)249+ extend(self.before_request_funcs, app.before_request_funcs)250+ extend(self.after_request_funcs, app.after_request_funcs)251+ extend(self.teardown_request_funcs, app.teardown_request_funcs)252+ extend(self.url_default_functions, app.url_default_functions)253+ extend(self.url_value_preprocessors, app.url_value_preprocessors)254+ extend(self.template_context_processors, app.template_context_processors)255+ update(self.error_handler_spec, app.error_handler_spec)256 275- merge_dict_nested(self.error_handler_spec, app.error_handler_spec)276-257 for deferred in self.deferred_functions:258 deferred(state)259 280- cli_resolved_group = options.get("cli_group", self.cli_group)281-260 if not self.cli.commands:261 return262 263+ cli_resolved_group = options.get("cli_group", self.cli_group)264+265 if cli_resolved_group is None:266 app.cli.commands.update(self.cli.commands)267 elif cli_resolved_group is _sentinel:268 self.cli.name = self.name177 unmodified linesmodified:src/flask/helpers.py-303 removed
1 import os2-import pkgutil2 import socket4-import sys3 import warnings4 from functools import update_wrapper5 from threading import RLock6 7 import werkzeug.utils10-from jinja2 import FileSystemLoader8 from werkzeug.exceptions import NotFound9 from werkzeug.routing import BuildError10 from werkzeug.urls import url_quote11 661 unmodified lines673 directory, path, **_prepare_send_file_kwargs(**kwargs)674 )675 676 680-def get_root_path(import_name):681- """Returns the path to a package or cwd if that cannot be found. This682- returns the path of a package or the folder that contains a module.683-684- Not to be confused with the package path returned by :func:`find_package`.685- """686- # Module already imported and has a file attribute. Use that first.687- mod = sys.modules.get(import_name)688- if mod is not None and hasattr(mod, "__file__"):689- return os.path.dirname(os.path.abspath(mod.__file__))690-691- # Next attempt: check the loader.692- loader = pkgutil.get_loader(import_name)693-694- # Loader does not exist or we're referring to an unloaded main module695- # or a main module without path (interactive sessions), go with the696- # current working directory.697- if loader is None or import_name == "__main__":698- return os.getcwd()699-700- if hasattr(loader, "get_filename"):701- filepath = loader.get_filename(import_name)702- else:703- # Fall back to imports.704- __import__(import_name)705- mod = sys.modules[import_name]706- filepath = getattr(mod, "__file__", None)707-708- # If we don't have a filepath it might be because we are a709- # namespace package. In this case we pick the root path from the710- # first module that is contained in our package.711- if filepath is None:712- raise RuntimeError(713- "No root path can be found for the provided module"714- f" {import_name!r}. This can happen because the module"715- " came from an import hook that does not provide file"716- " name information or because it's a namespace package."717- " In this case the root path needs to be explicitly"718- " provided."719- )720-721- # filepath is import_name.py for a module, or __init__.py for a package.722- return os.path.dirname(os.path.abspath(filepath))723-724-725-def _matching_loader_thinks_module_is_package(loader, mod_name):726- """Given the loader that loaded a module and the module this function727- attempts to figure out if the given module is actually a package.728- """729- cls = type(loader)730- # If the loader can tell us if something is a package, we can731- # directly ask the loader.732- if hasattr(loader, "is_package"):733- return loader.is_package(mod_name)734- # importlib's namespace loaders do not have this functionality but735- # all the modules it loads are packages, so we can take advantage of736- # this information.737- elif cls.__module__ == "_frozen_importlib" and cls.__name__ == "NamespaceLoader":738- return True739- # Otherwise we need to fail with an error that explains what went740- # wrong.741- raise AttributeError(742- f"{cls.__name__}.is_package() method is missing but is required"743- " for PEP 302 import hooks."744- )745-746-747-def _find_package_path(root_mod_name):748- """Find the path where the module's root exists in"""749- import importlib.util750-751- try:752- spec = importlib.util.find_spec(root_mod_name)753- if spec is None:754- raise ValueError("not found")755- # ImportError: the machinery told us it does not exist756- # ValueError:757- # - the module name was invalid758- # - the module name is __main__759- # - *we* raised `ValueError` due to `spec` being `None`760- except (ImportError, ValueError):761- pass # handled below762- else:763- # namespace package764- if spec.origin in {"namespace", None}:765- return os.path.dirname(next(iter(spec.submodule_search_locations)))766- # a package (with __init__.py)767- elif spec.submodule_search_locations:768- return os.path.dirname(os.path.dirname(spec.origin))769- # just a normal module770- else:771- return os.path.dirname(spec.origin)772-773- # we were unable to find the `package_path` using PEP 451 loaders774- loader = pkgutil.get_loader(root_mod_name)775- if loader is None or root_mod_name == "__main__":776- # import name is not found, or interactive/main module777- return os.getcwd()778- else:779- if hasattr(loader, "get_filename"):780- filename = loader.get_filename(root_mod_name)781- elif hasattr(loader, "archive"):782- # zipimporter's loader.archive points to the .egg or .zip783- # archive filename is dropped in call to dirname below.784- filename = loader.archive785- else:786- # At least one loader is missing both get_filename and archive:787- # Google App Engine's HardenedModulesHook788- #789- # Fall back to imports.790- __import__(root_mod_name)791- filename = sys.modules[root_mod_name].__file__792- package_path = os.path.abspath(os.path.dirname(filename))793-794- # In case the root module is a package we need to chop of the795- # rightmost part. This needs to go through a helper function796- # because of namespace packages.797- if _matching_loader_thinks_module_is_package(loader, root_mod_name):798- package_path = os.path.dirname(package_path)799-800- return package_path801-802-803-def find_package(import_name):804- """Finds a package and returns the prefix (or None if the package is805- not installed) as well as the folder that contains the package or806- module as a tuple. The package path returned is the module that would807- have to be added to the pythonpath in order to make it possible to808- import the module. The prefix is the path below which a UNIX like809- folder structure exists (lib, share etc.).810- """811- root_mod_name, _, _ = import_name.partition(".")812- package_path = _find_package_path(root_mod_name)813- site_parent, site_folder = os.path.split(package_path)814- py_prefix = os.path.abspath(sys.prefix)815- if package_path.startswith(py_prefix):816- return py_prefix, package_path817- elif site_folder.lower() == "site-packages":818- parent, folder = os.path.split(site_parent)819- # Windows like installations820- if folder.lower() == "lib":821- base_dir = parent822- # UNIX like installations823- elif os.path.basename(parent).lower() == "lib":824- base_dir = os.path.dirname(parent)825- else:826- base_dir = site_parent827- return base_dir, package_path828- return None, package_path829-830-677 class locked_cached_property:678 """A decorator that converts a function into a lazy property. The679 function wrapped is called the first time to retrieve the result680 and then that calculated result is used the next time you access18 unmodified lines699 obj.__dict__[self.__name__] = value700 return value701 702 857-class _PackageBoundObject:858- #: The name of the package or module that this app belongs to. Do not859- #: change this once it is set by the constructor.860- import_name = None861-862- #: Location of the template files to be added to the template lookup.863- #: ``None`` if templates should not be added.864- template_folder = None865-866- #: Absolute path to the package on the filesystem. Used to look up867- #: resources contained in the package.868- root_path = None869-870- def __init__(self, import_name, template_folder=None, root_path=None):871- self.import_name = import_name872- self.template_folder = template_folder873-874- if root_path is None:875- root_path = get_root_path(self.import_name)876-877- self.root_path = root_path878- self._static_folder = None879- self._static_url_path = None880-881- # circular import882- from .cli import AppGroup883-884- #: The Click command group for registration of CLI commands885- #: on the application and associated blueprints. These commands886- #: are accessible via the :command:`flask` command once the887- #: application has been discovered and blueprints registered.888- self.cli = AppGroup()889-890- @property891- def static_folder(self):892- """The absolute path to the configured static folder."""893- if self._static_folder is not None:894- return os.path.join(self.root_path, self._static_folder)895-896- @static_folder.setter897- def static_folder(self, value):898- if value is not None:899- value = os.fspath(value).rstrip(r"\/")900- self._static_folder = value901-902- @property903- def static_url_path(self):904- """The URL prefix that the static route will be accessible from.905-906- If it was not configured during init, it is derived from907- :attr:`static_folder`.908- """909- if self._static_url_path is not None:910- return self._static_url_path911-912- if self.static_folder is not None:913- basename = os.path.basename(self.static_folder)914- return f"/{basename}".rstrip("/")915-916- @static_url_path.setter917- def static_url_path(self, value):918- if value is not None:919- value = value.rstrip("/")920-921- self._static_url_path = value922-923- @property924- def has_static_folder(self):925- """This is ``True`` if the package bound object's container has a926- folder for static files.927-928- .. versionadded:: 0.5929- """930- return self.static_folder is not None931-932- @locked_cached_property933- def jinja_loader(self):934- """The Jinja loader for this package bound object.935-936- .. versionadded:: 0.5937- """938- if self.template_folder is not None:939- return FileSystemLoader(os.path.join(self.root_path, self.template_folder))940-941- def get_send_file_max_age(self, filename):942- """Used by :func:`send_file` to determine the ``max_age`` cache943- value for a given file path if it wasn't passed.944-945- By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from946- the configuration of :data:`~flask.current_app`. This defaults947- to ``None``, which tells the browser to use conditional requests948- instead of a timed cache, which is usually preferable.949-950- .. versionchanged:: 2.0951- The default configuration is ``None`` instead of 12 hours.952-953- .. versionadded:: 0.9954- """955- value = current_app.send_file_max_age_default956-957- if value is None:958- return None959-960- return total_seconds(value)961-962- def send_static_file(self, filename):963- """Function used internally to send static files from the static964- folder to the browser.965-966- .. versionadded:: 0.5967- """968- if not self.has_static_folder:969- raise RuntimeError("No static folder for this object")970-971- # send_file only knows to call get_send_file_max_age on the app,972- # call it here so it works for blueprints too.973- max_age = self.get_send_file_max_age(filename)974- return send_from_directory(self.static_folder, filename, max_age=max_age)975-976- def open_resource(self, resource, mode="rb"):977- """Opens a resource from the application's resource folder. To see978- how this works, consider the following folder structure::979-980- /myapplication.py981- /schema.sql982- /static983- /style.css984- /templates985- /layout.html986- /index.html987-988- If you want to open the :file:`schema.sql` file you would do the989- following::990-991- with app.open_resource('schema.sql') as f:992- contents = f.read()993- do_something_with(contents)994-995- :param resource: the name of the resource. To access resources within996- subfolders use forward slashes as separator.997- :param mode: Open file in this mode. Only reading is supported,998- valid values are "r" (or "rt") and "rb".999- """1000- if mode not in {"r", "rt", "rb"}:1001- raise ValueError("Resources can only be opened for reading")1002-1003- return open(os.path.join(self.root_path, resource), mode)1004-1005-703 def total_seconds(td):704 """Returns the total seconds from a timedelta object.705 706 :param timedelta td: the timedelta to be converted in seconds25 unmodified linesmodified:src/flask/scaffold.py+536 added-128 removed
1+import importlib.util2+import os3+import pkgutil4+import sys5 from collections import defaultdict6 from functools import update_wrapper7 8+from jinja2 import FileSystemLoader9 from werkzeug.exceptions import default_exceptions10 from werkzeug.exceptions import HTTPException11 7-from .helpers import _PackageBoundObject12+from .cli import AppGroup13+from .globals import current_app14+from .helpers import locked_cached_property15+from .helpers import send_from_directory16 from .templating import _default_template_ctx_processor17 18 # a singleton sentinel value for parameter defaults19 _sentinel = object()6 unmodified lines26 27 def wrapper_func(self, *args, **kwargs):28 if self._is_setup_finished():29 raise AssertionError(22- "A setup function was called after the "23- "first request was handled. This usually indicates a bug "24- "in the application where a module was not imported "25- "and decorators or other functionality was called too late.\n"26- "To fix this make sure to import all your view modules, "27- "database models and everything related at a central place "28- "before the application starts serving requests."30+ "A setup function was called after the first request "31+ "was handled. This usually indicates a bug in the"32+ " application where a module was not imported and"33+ " decorators or other functionality was called too"34+ " late.\nTo fix this make sure to import all your view"35+ " modules, database models, and everything related at a"36+ " central place before the application starts serving"37+ " requests."38 )39 return f(self, *args, **kwargs)40 41 return update_wrapper(wrapper_func, f)42 43 35-class Scaffold(_PackageBoundObject):36- """A common base for class Flask and class Blueprint."""44+class Scaffold:45+ """Common behavior shared between :class:`~flask.Flask` and46+ :class:`~flask.blueprints.Blueprint`.47 38- #: Skeleton local JSON decoder class to use.39- #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_encoder`.40- json_encoder = None48+ :param import_name: The import name of the module where this object49+ is defined. Usually :attr:`__name__` should be used.50+ :param static_folder: Path to a folder of static files to serve.51+ If this is set, a static route will be added.52+ :param static_url_path: URL prefix for the static route.53+ :param template_folder: Path to a folder containing template files.54+ for rendering. If this is set, a Jinja loader will be added.55+ :param root_path: The path that static, template, and resource files56+ are relative to. Typically not set, it is discovered based on57+ the ``import_name``.58 42- #: Skeleton local JSON decoder class to use.43- #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_decoder`.44- json_decoder = None59+ .. versionadded:: 2.0.060+ """61 46- #: The name of the package or module that this app belongs to. Do not47- #: change this once it is set by the constructor.48- import_name = None62+ name: str63+ _static_folder = None64+ _static_url_path = None65 50- #: Location of the template files to be added to the template lookup.51- #: ``None`` if templates should not be added.52- template_folder = None66+ #: JSON encoder class used by :func:`flask.json.dumps`. If a67+ #: blueprint sets this, it will be used instead of the app's value.68+ json_encoder = None69 54- #: Absolute path to the package on the filesystem. Used to look up55- #: resources contained in the package.56- root_path = None70+ #: JSON decoder class used by :func:`flask.json.loads`. If a71+ #: blueprint sets this, it will be used instead of the app's value.72+ json_decoder = None73 74 def __init__(75 self,76 import_name,61- static_folder="static",77+ static_folder=None,78 static_url_path=None,79 template_folder=None,80 root_path=None,81 ):66- super().__init__(67- import_name=import_name,68- template_folder=template_folder,69- root_path=root_path,70- )82+ #: The name of the package or module that this object belongs83+ #: to. Do not change this once it is set by the constructor.84+ self.import_name = import_name85+86 self.static_folder = static_folder87 self.static_url_path = static_url_path88 74- #: A dictionary of all view functions registered. The keys will75- #: be function names which are also used to generate URLs and76- #: the values are the function objects themselves.89+ #: The path to the templates folder, relative to90+ #: :attr:`root_path`, to add to the template loader. ``None`` if91+ #: templates should not be added.92+ self.template_folder = template_folder93+94+ if root_path is None:95+ root_path = get_root_path(self.import_name)96+97+ #: Absolute path to the package on the filesystem. Used to look98+ #: up resources contained in the package.99+ self.root_path = root_path100+101+ #: The Click command group for registering CLI commands for this102+ #: object. The commands are available from the ``flask`` command103+ #: once the application has been discovered and blueprints have104+ #: been registered.105+ self.cli = AppGroup()106+107+ #: A dictionary mapping endpoint names to view functions.108+ #:109 #: To register a view function, use the :meth:`route` decorator.110+ #:111+ #: This data structure is internal. It should not be modified112+ #: directly and its format may change at any time.113 self.view_functions = {}114 80- #: A dictionary of all registered error handlers. The key is ``None``81- #: for error handlers active on the application, otherwise the key is82- #: the name of the blueprint. Each key points to another dictionary83- #: where the key is the status code of the http exception. The84- #: special key ``None`` points to a list of tuples where the first item85- #: is the class for the instance check and the second the error handler86- #: function.115+ #: A data structure of registered error handlers, in the format116+ #: ``{scope: {code: {class: handler}}}```. The ``scope`` key is117+ #: the name of a blueprint the handlers are active for, or118+ #: ``None`` for all requests. The ``code`` key is the HTTP119+ #: status code for ``HTTPException``, or ``None`` for120+ #: other exceptions. The innermost dictionary maps exception121+ #: classes to handler functions.122 #:123 #: To register an error handler, use the :meth:`errorhandler`124 #: decorator.125+ #:126+ #: This data structure is internal. It should not be modified127+ #: directly and its format may change at any time.128 self.error_handler_spec = defaultdict(lambda: defaultdict(dict))129 92- #: A dictionary with lists of functions that will be called at the93- #: beginning of each request. The key of the dictionary is the name of94- #: the blueprint this function is active for, or ``None`` for all95- #: requests. To register a function, use the :meth:`before_request`130+ #: A data structure of functions to call at the beginning of131+ #: each request, in the format ``{scope: [functions]}``. The132+ #: ``scope`` key is the name of a blueprint the functions are133+ #: active for, or ``None`` for all requests.134+ #:135+ #: To register a function, use the :meth:`before_request`136 #: decorator.137+ #:138+ #: This data structure is internal. It should not be modified139+ #: directly and its format may change at any time.140 self.before_request_funcs = defaultdict(list)141 99- #: A dictionary with lists of functions that should be called after100- #: each request. The key of the dictionary is the name of the blueprint101- #: this function is active for, ``None`` for all requests. This can for102- #: example be used to close database connections. To register a function103- #: here, use the :meth:`after_request` decorator.142+ #: A data structure of functions to call at the end of each143+ #: request, in the format ``{scope: [functions]}``. The144+ #: ``scope`` key is the name of a blueprint the functions are145+ #: active for, or ``None`` for all requests.146+ #:147+ #: To register a function, use the :meth:`after_request`148+ #: decorator.149+ #:150+ #: This data structure is internal. It should not be modified151+ #: directly and its format may change at any time.152 self.after_request_funcs = defaultdict(list)153 106- #: A dictionary with lists of functions that are called after107- #: each request, even if an exception has occurred. The key of the108- #: dictionary is the name of the blueprint this function is active for,109- #: ``None`` for all requests. These functions are not allowed to modify110- #: the request, and their return values are ignored. If an exception111- #: occurred while processing the request, it gets passed to each112- #: teardown_request function. To register a function here, use the113- #: :meth:`teardown_request` decorator.154+ #: A data structure of functions to call at the end of each155+ #: request even if an exception is raised, in the format156+ #: ``{scope: [functions]}``. The ``scope`` key is the name of a157+ #: blueprint the functions are active for, or ``None`` for all158+ #: requests.159 #:115- #: .. versionadded:: 0.7160+ #: To register a function, use the :meth:`teardown_request`161+ #: decorator.162+ #:163+ #: This data structure is internal. It should not be modified164+ #: directly and its format may change at any time.165 self.teardown_request_funcs = defaultdict(list)166 118- #: A dictionary with list of functions that are called without argument119- #: to populate the template context. The key of the dictionary is the120- #: name of the blueprint this function is active for, ``None`` for all121- #: requests. Each returns a dictionary that the template context is122- #: updated with. To register a function here, use the123- #: :meth:`context_processor` decorator.167+ #: A data structure of functions to call to pass extra context168+ #: values when rendering templates, in the format169+ #: ``{scope: [functions]}``. The ``scope`` key is the name of a170+ #: blueprint the functions are active for, or ``None`` for all171+ #: requests.172+ #:173+ #: To register a function, use the :meth:`context_processor`174+ #: decorator.175+ #:176+ #: This data structure is internal. It should not be modified177+ #: directly and its format may change at any time.178 self.template_context_processors = defaultdict(179 list, {None: [_default_template_ctx_processor]}180 )181 128- #: A dictionary with lists of functions that are called before the129- #: :attr:`before_request_funcs` functions. The key of the dictionary is130- #: the name of the blueprint this function is active for, or ``None``131- #: for all requests. To register a function, use132- #: :meth:`url_value_preprocessor`.182+ #: A data structure of functions to call to modify the keyword183+ #: arguments passed to the view function, in the format184+ #: ``{scope: [functions]}``. The ``scope`` key is the name of a185+ #: blueprint the functions are active for, or ``None`` for all186+ #: requests.187 #:134- #: .. versionadded:: 0.7188+ #: To register a function, use the189+ #: :meth:`url_value_preprocessor` decorator.190+ #:191+ #: This data structure is internal. It should not be modified192+ #: directly and its format may change at any time.193 self.url_value_preprocessors = defaultdict(list)194 137- #: A dictionary with lists of functions that can be used as URL value138- #: preprocessors. The key ``None`` here is used for application wide139- #: callbacks, otherwise the key is the name of the blueprint.140- #: Each of these functions has the chance to modify the dictionary141- #: of URL values before they are used as the keyword arguments of the142- #: view function. For each function registered this one should also143- #: provide a :meth:`url_defaults` function that adds the parameters144- #: automatically again that were removed that way.195+ #: A data structure of functions to call to modify the keyword196+ #: arguments when generating URLs, in the format197+ #: ``{scope: [functions]}``. The ``scope`` key is the name of a198+ #: blueprint the functions are active for, or ``None`` for all199+ #: requests.200 #:146- #: .. versionadded:: 0.7201+ #: To register a function, use the :meth:`url_defaults`202+ #: decorator.203+ #:204+ #: This data structure is internal. It should not be modified205+ #: directly and its format may change at any time.206 self.url_default_functions = defaultdict(list)207 208+ def __repr__(self):209+ return f"<{type(self).__name__} {self.name!r}>"210+211 def _is_setup_finished(self):212 raise NotImplementedError213 214+ @property215+ def static_folder(self):216+ """The absolute path to the configured static folder. ``None``217+ if no static folder is set.218+ """219+ if self._static_folder is not None:220+ return os.path.join(self.root_path, self._static_folder)221+222+ @static_folder.setter223+ def static_folder(self, value):224+ if value is not None:225+ value = os.fspath(value).rstrip(r"\/")226+227+ self._static_folder = value228+229+ @property230+ def has_static_folder(self):231+ """``True`` if :attr:`static_folder` is set.232+233+ .. versionadded:: 0.5234+ """235+ return self.static_folder is not None236+237+ @property238+ def static_url_path(self):239+ """The URL prefix that the static route will be accessible from.240+241+ If it was not configured during init, it is derived from242+ :attr:`static_folder`.243+ """244+ if self._static_url_path is not None:245+ return self._static_url_path246+247+ if self.static_folder is not None:248+ basename = os.path.basename(self.static_folder)249+ return f"/{basename}".rstrip("/")250+251+ @static_url_path.setter252+ def static_url_path(self, value):253+ if value is not None:254+ value = value.rstrip("/")255+256+ self._static_url_path = value257+258+ def get_send_file_max_age(self, filename):259+ """Used by :func:`send_file` to determine the ``max_age`` cache260+ value for a given file path if it wasn't passed.261+262+ By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from263+ the configuration of :data:`~flask.current_app`. This defaults264+ to ``None``, which tells the browser to use conditional requests265+ instead of a timed cache, which is usually preferable.266+267+ .. versionchanged:: 2.0268+ The default configuration is ``None`` instead of 12 hours.269+270+ .. versionadded:: 0.9271+ """272+ value = current_app.send_file_max_age_default273+274+ if value is None:275+ return None276+277+ return int(value.total_seconds())278+279+ def send_static_file(self, filename):280+ """The view function used to serve files from281+ :attr:`static_folder`. A route is automatically registered for282+ this view at :attr:`static_url_path` if :attr:`static_folder` is283+ set.284+285+ .. versionadded:: 0.5286+ """287+ if not self.has_static_folder:288+ raise RuntimeError("'static_folder' must be set to serve static_files.")289+290+ # send_file only knows to call get_send_file_max_age on the app,291+ # call it here so it works for blueprints too.292+ max_age = self.get_send_file_max_age(filename)293+ return send_from_directory(self.static_folder, filename, max_age=max_age)294+295+ @locked_cached_property296+ def jinja_loader(self):297+ """The Jinja loader for this object's templates. By default this298+ is a class :class:`jinja2.loaders.FileSystemLoader` to299+ :attr:`template_folder` if it is set.300+301+ .. versionadded:: 0.5302+ """303+ if self.template_folder is not None:304+ return FileSystemLoader(os.path.join(self.root_path, self.template_folder))305+306+ def open_resource(self, resource, mode="rb"):307+ """Open a resource file relative to :attr:`root_path` for308+ reading.309+310+ For example, if the file ``schema.sql`` is next to the file311+ ``app.py`` where the ``Flask`` app is defined, it can be opened312+ with:313+314+ .. code-block:: python315+316+ with app.open_resource("schema.sql") as f:317+ conn.executescript(f.read())318+319+ :param resource: Path to the resource relative to320+ :attr:`root_path`.321+ :param mode: Open the file in this mode. Only reading is322+ supported, valid values are "r" (or "rt") and "rb".323+ """324+ if mode not in {"r", "rt", "rb"}:325+ raise ValueError("Resources can only be opened for reading.")326+327+ return open(os.path.join(self.root_path, resource), mode)328+329 def _method_route(self, method, rule, options):330 if "methods" in options:331 raise TypeError("Use the 'route' decorator to use the 'methods' argument.")332 34 unmodified lines367 """368 return self._method_route("PATCH", rule, options)369 370 def route(self, rule, **options):194- """A decorator that is used to register a view function for a195- given URL rule. This does the same thing as :meth:`add_url_rule`196- but is intended for decorator usage::371+ """Decorate a view function to register it with the given URL372+ rule and options. Calls :meth:`add_url_rule`, which has more373+ details about the implementation.374 375+ .. code-block:: python376+198- @app.route('/')377+ @app.route("/")378 def index():200- return 'Hello World'379+ return "Hello, World!"380 202- For more information refer to :ref:`url-route-registrations`.381+ See :ref:`url-route-registrations`.382 204- :param rule: the URL rule as string205- :param endpoint: the endpoint for the registered URL rule. Flask206- itself assumes the name of the view function as207- endpoint208- :param options: the options to be forwarded to the underlying209- :class:`~werkzeug.routing.Rule` object. A change210- to Werkzeug is handling of method options. methods211- is a list of methods this rule should be limited212- to (``GET``, ``POST`` etc.). By default a rule213- just listens for ``GET`` (and implicitly ``HEAD``).214- Starting with Flask 0.6, ``OPTIONS`` is implicitly215- added and handled by the standard request handling.383+ The endpoint name for the route defaults to the name of the view384+ function if the ``endpoint`` parameter isn't passed.385+386+ The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and387+ ``OPTIONS`` are added automatically.388+389+ :param rule: The URL rule string.390+ :param options: Extra options passed to the391+ :class:`~werkzeug.routing.Rule` object.392 """393 394 def decorator(f):395 endpoint = options.pop("endpoint", None)10 unmodified lines406 view_func=None,407 provide_automatic_options=None,408 **options,409 ):410+ """Register a rule for routing incoming requests and building411+ URLs. The :meth:`route` decorator is a shortcut to call this412+ with the ``view_func`` argument. These are equivalent:413+414+ .. code-block:: python415+416+ @app.route("/")417+ def index():418+ ...419+420+ .. code-block:: python421+422+ def index():423+ ...424+425+ app.add_url_rule("/", view_func=index)426+427+ See :ref:`url-route-registrations`.428+429+ The endpoint name for the route defaults to the name of the view430+ function if the ``endpoint`` parameter isn't passed. An error431+ will be raised if a function has already been registered for the432+ endpoint.433+434+ The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` is435+ always added automatically, and ``OPTIONS`` is added436+ automatically by default.437+438+ ``view_func`` does not necessarily need to be passed, but if the439+ rule should participate in routing an endpoint name must be440+ associated with a view function at some point with the441+ :meth:`endpoint` decorator.442+443+ .. code-block:: python444+445+ app.add_url_rule("/", endpoint="index")446+447+ @app.endpoint("index")448+ def index():449+ ...450+451+ If ``view_func`` has a ``required_methods`` attribute, those452+ methods are added to the passed and automatic methods. If it453+ has a ``provide_automatic_methods`` attribute, it is used as the454+ default if the parameter is not passed.455+456+ :param rule: The URL rule string.457+ :param endpoint: The endpoint name to associate with the rule458+ and view function. Used when routing and building URLs.459+ Defaults to ``view_func.__name__``.460+ :param view_func: The view function to associate with the461+ endpoint name.462+ :param provide_automatic_options: Add the ``OPTIONS`` method and463+ respond to ``OPTIONS`` requests automatically.464+ :param options: Extra options passed to the465+ :class:`~werkzeug.routing.Rule` object.466+ """467 raise NotImplementedError468 469 def endpoint(self, endpoint):237- """A decorator to register a function as an endpoint.238- Example::470+ """Decorate a view function to register it for the given471+ endpoint. Used if a rule is added without a ``view_func`` with472+ :meth:`add_url_rule`.473 240- @app.endpoint('example.endpoint')474+ .. code-block:: python475+476+ app.add_url_rule("/ex", endpoint="example")477+478+ @app.endpoint("example")479 def example():242- return "example"480+ ...481 244- :param endpoint: the name of the endpoint482+ :param endpoint: The endpoint name to associate with the view483+ function.484 """485 486 def decorator(f):487 self.view_functions[endpoint] = f2 unmodified lines490 return decorator491 492 @setupmethod493 def before_request(self, f):255- """Registers a function to run before each request.494+ """Register a function to run before each request.495 257- For example, this can be used to open a database connection, or to load258- the logged in user from the session.496+ For example, this can be used to open a database connection, or497+ to load the logged in user from the session.498 260- The function will be called without any arguments. If it returns a261- non-None value, the value is handled as if it was the return value from262- the view, and further request handling is stopped.499+ .. code-block:: python500+501+ @app.before_request502+ def load_user():503+ if "user_id" in session:504+ g.user = db.session.get(session["user_id"])505+506+ The function will be called without any arguments. If it returns507+ a non-``None`` value, the value is handled as if it was the508+ return value from the view, and further request handling is509+ stopped.510 """511 self.before_request_funcs[None].append(f)512 return f513 514 @setupmethod515 def after_request(self, f):269- """Register a function to be run after each request.516+ """Register a function to run after each request to this object.517 271- Your function must take one parameter, an instance of272- :attr:`response_class` and return a new response object or the273- same (see :meth:`process_response`).518+ The function is called with the response object, and must return519+ a response object. This allows the functions to modify or520+ replace the response before it is sent.521 275- As of Flask 0.7 this function might not be executed at the end of the276- request in case an unhandled exception occurred.522+ If a function raises an exception, any remaining523+ ``after_request`` functions will not be called. Therefore, this524+ should not be used for actions that must execute, such as to525+ close resources. Use :meth:`teardown_request` for that.526 """527 self.after_request_funcs[None].append(f)528 return f529 15 unmodified lines545 functions are called just before the request context moves from the546 stack of active contexts. This becomes relevant if you are using547 such constructs in tests.548 300- Generally teardown functions must take every necessary step to avoid301- that they will fail. If they do execute code that might fail they549+ Teardown functions must avoid raising exceptions, since they . If they550+ execute code that might fail they551 will have to surround the execution of these code by try/except552 statements and log occurring errors.553 554 When a teardown function was called because of an exception it will74 unmodified lines629 an arbitrary exception630 """631 632 def decorator(f):384- self._register_error_handler(None, code_or_exception, f)633+ self.register_error_handler(code_or_exception, f)634 return f635 636 return decorator637 4 unmodified lines642 usage.643 644 .. versionadded:: 0.7645 """397- self._register_error_handler(None, code_or_exception, f)398-399- @setupmethod400- def _register_error_handler(self, key, code_or_exception, f):401- """402- :type key: None|str403- :type code_or_exception: int|T<=Exception404- :type f: callable405- """646 if isinstance(code_or_exception, HTTPException): # old broken behavior647 raise ValueError(648 "Tried to register a handler for an exception instance"649 f" {code_or_exception!r}. Handlers can only be"8 unmodified lines658 " code. Use a subclass of HTTPException with that code"659 " instead."660 )661 422- self.error_handler_spec[key][code][exc_class] = f662+ self.error_handler_spec[None][code][exc_class] = f663 664 @staticmethod665 def _get_exc_class_and_code(exc_class_or_code):666 """Get the exception class being handled. For HTTP status codes23 unmodified lines690 function. This always is the function name.691 """692 assert view_func is not None, "expected view func if endpoint is not provided."693 return view_func.__name__694+695+696+def get_root_path(import_name):697+ """Find the root path of a package, or the path that contains a698+ module. If it cannot be found, returns the current working699+ directory.700+701+ Not to be confused with the value returned by :func:`find_package`.702+703+ :meta private:704+ """705+ # Module already imported and has a file attribute. Use that first.706+ mod = sys.modules.get(import_name)707+708+ if mod is not None and hasattr(mod, "__file__"):709+ return os.path.dirname(os.path.abspath(mod.__file__))710+711+ # Next attempt: check the loader.712+ loader = pkgutil.get_loader(import_name)713+714+ # Loader does not exist or we're referring to an unloaded main715+ # module or a main module without path (interactive sessions), go716+ # with the current working directory.717+ if loader is None or import_name == "__main__":718+ return os.getcwd()719+720+ if hasattr(loader, "get_filename"):721+ filepath = loader.get_filename(import_name)722+ else:723+ # Fall back to imports.724+ __import__(import_name)725+ mod = sys.modules[import_name]726+ filepath = getattr(mod, "__file__", None)727+728+ # If we don't have a file path it might be because it is a729+ # namespace package. In this case pick the root path from the730+ # first module that is contained in the package.731+ if filepath is None:732+ raise RuntimeError(733+ "No root path can be found for the provided module"734+ f" {import_name!r}. This can happen because the module"735+ " came from an import hook that does not provide file"736+ " name information or because it's a namespace package."737+ " In this case the root path needs to be explicitly"738+ " provided."739+ )740+741+ # filepath is import_name.py for a module, or __init__.py for a package.742+ return os.path.dirname(os.path.abspath(filepath))743+744+745+def _matching_loader_thinks_module_is_package(loader, mod_name):746+ """Attempt to figure out if the given name is a package or a module.747+748+ :param: loader: The loader that handled the name.749+ :param mod_name: The name of the package or module.750+ """751+ # Use loader.is_package if it's available.752+ if hasattr(loader, "is_package"):753+ return loader.is_package(mod_name)754+755+ cls = type(loader)756+757+ # NamespaceLoader doesn't implement is_package, but all names it758+ # loads must be packages.759+ if cls.__module__ == "_frozen_importlib" and cls.__name__ == "NamespaceLoader":760+ return True761+762+ # Otherwise we need to fail with an error that explains what went763+ # wrong.764+ raise AttributeError(765+ f"'{cls.__name__}.is_package()' must be implemented for PEP 302"766+ f" import hooks."767+ )768+769+770+def _find_package_path(root_mod_name):771+ """Find the path that contains the package or module."""772+ try:773+ spec = importlib.util.find_spec(root_mod_name)774+775+ if spec is None:776+ raise ValueError("not found")777+ # ImportError: the machinery told us it does not exist778+ # ValueError:779+ # - the module name was invalid780+ # - the module name is __main__781+ # - *we* raised `ValueError` due to `spec` being `None`782+ except (ImportError, ValueError):783+ pass # handled below784+ else:785+ # namespace package786+ if spec.origin in {"namespace", None}:787+ return os.path.dirname(next(iter(spec.submodule_search_locations)))788+ # a package (with __init__.py)789+ elif spec.submodule_search_locations:790+ return os.path.dirname(os.path.dirname(spec.origin))791+ # just a normal module792+ else:793+ return os.path.dirname(spec.origin)794+795+ # we were unable to find the `package_path` using PEP 451 loaders796+ loader = pkgutil.get_loader(root_mod_name)797+798+ if loader is None or root_mod_name == "__main__":799+ # import name is not found, or interactive/main module800+ return os.getcwd()801+802+ if hasattr(loader, "get_filename"):803+ filename = loader.get_filename(root_mod_name)804+ elif hasattr(loader, "archive"):805+ # zipimporter's loader.archive points to the .egg or .zip file.806+ filename = loader.archive807+ else:808+ # At least one loader is missing both get_filename and archive:809+ # Google App Engine's HardenedModulesHook, use __file__.810+ filename = importlib.import_module(root_mod_name).__file__811+812+ package_path = os.path.abspath(os.path.dirname(filename))813+814+ # If the imported name is a package, filename is currently pointing815+ # to the root of the package, need to get the current directory.816+ if _matching_loader_thinks_module_is_package(loader, root_mod_name):817+ package_path = os.path.dirname(package_path)818+819+ return package_path820+821+822+def find_package(import_name):823+ """Find the prefix that a package is installed under, and the path824+ that it would be imported from.825+826+ The prefix is the directory containing the standard directory827+ hierarchy (lib, bin, etc.). If the package is not installed to the828+ system (:attr:`sys.prefix`) or a virtualenv (``site-packages``),829+ ``None`` is returned.830+831+ The path is the entry in :attr:`sys.path` that contains the package832+ for import. If the package is not installed, it's assumed that the833+ package was imported from the current working directory.834+ """835+ root_mod_name, _, _ = import_name.partition(".")836+ package_path = _find_package_path(root_mod_name)837+ py_prefix = os.path.abspath(sys.prefix)838+839+ # installed to the system840+ if package_path.startswith(py_prefix):841+ return py_prefix, package_path842+843+ site_parent, site_folder = os.path.split(package_path)844+845+ # installed to a virtualenv846+ if site_folder.lower() == "site-packages":847+ parent, folder = os.path.split(site_parent)848+849+ # Windows (prefix/lib/site-packages)850+ if folder.lower() == "lib":851+ return parent, package_path852+853+ # Unix (prefix/lib/pythonX.Y/site-packages)854+ if os.path.basename(parent).lower() == "lib":855+ return os.path.dirname(parent), package_path856+857+ # something else (prefix/site-packages)858+ return site_parent, package_path859+860+ # not installed861+ return None, package_path