move _PackageBoundObject into Scaffold
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent 3316604 · Browse files · 3 files·+343 added−352 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+343 added−352 removed
- other:+343 added−352 removed
Provenance
- Commit
9f7c602- Tree
6689d56- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
3316604
3 files changed+343 added−352 removed
modified:src/flask/app.py+1 added-4 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_down1978 unmodified lines2025 """The WSGI server calls the Flask application object as the2026 WSGI application. This calls :meth:`wsgi_app` which can be2027 wrapped to applying middleware."""2028 return self.wsgi_app(environ, start_response)2029-2030- def __repr__(self):2031- return f"<{type(self).__name__} {self.name!r}>"modified: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+342 added-45 removed
1+import os2+import pkgutil3+import sys4 from collections import defaultdict5 from functools import update_wrapper6 7+from jinja2 import FileSystemLoader8 from werkzeug.exceptions import default_exceptions9 from werkzeug.exceptions import HTTPException10 7-from .helpers import _PackageBoundObject11+from .cli import AppGroup12+from .globals import current_app13+from .helpers import locked_cached_property14+from .helpers import send_from_directory15 from .templating import _default_template_ctx_processor16 17 # a singleton sentinel value for parameter defaults18 _sentinel = object()6 unmodified lines25 26 def wrapper_func(self, *args, **kwargs):27 if self._is_setup_finished():28 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."29+ "A setup function was called after the first request "30+ "was handled. This usually indicates a bug in the"31+ " application where a module was not imported and"32+ " decorators or other functionality was called too"33+ " late.\nTo fix this make sure to import all your view"34+ " modules, database models, and everything related at a"35+ " central place before the application starts serving"36+ " requests."37 )38 return f(self, *args, **kwargs)39 40 return update_wrapper(wrapper_func, f)41 42 35-class Scaffold(_PackageBoundObject):36- """A common base for class Flask and class Blueprint."""43+class Scaffold:44+ """A common base for :class:`~flask.app.Flask` and45+ :class:`~flask.blueprints.Blueprint`.46+ """47 48+ name: str49+ _static_folder = None50+ _static_url_path = None51+52 #: Skeleton local JSON decoder class to use.53 #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_encoder`.54 json_encoder = None55 56 #: Skeleton local JSON decoder class to use.57 #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_decoder`.58 json_decoder = None59 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 = None49-50- #: Location of the template files to be added to the template lookup.51- #: ``None`` if templates should not be added.52- template_folder = None53-54- #: Absolute path to the package on the filesystem. Used to look up55- #: resources contained in the package.56- root_path = None57-60 def __init__(61 self,62 import_name,63 static_folder="static",64 static_url_path=None,65 template_folder=None,66 root_path=None,67 ):66- super().__init__(67- import_name=import_name,68- template_folder=template_folder,69- root_path=root_path,70- )68+ #: The name of the package or module that this object belongs69+ #: to. Do not change this once it is set by the constructor.70+ self.import_name = import_name71+72 self.static_folder = static_folder73 self.static_url_path = static_url_path74 75+ #: The path to the templates folder, relative to76+ #: :attr:`root_path`, to add to the template loader. ``None`` if77+ #: templates should not be added.78+ self.template_folder = template_folder79+80+ if root_path is None:81+ root_path = get_root_path(self.import_name)82+83+ #: Absolute path to the package on the filesystem. Used to look84+ #: up resources contained in the package.85+ self.root_path = root_path86+87+ #: The Click command group for registering CLI commands for this88+ #: object. The commands are available from the ``flask`` command89+ #: once the application has been discovered and blueprints have90+ #: been registered.91+ self.cli = AppGroup()92+93 #: A dictionary of all view functions registered. The keys will94 #: be function names which are also used to generate URLs and95 #: the values are the function objects themselves.96 #: To register a view function, use the :meth:`route` decorator.67 unmodified lines164 #:165 #: .. versionadded:: 0.7166 self.url_default_functions = defaultdict(list)167 168+ def __repr__(self):169+ return f"<{type(self).__name__} {self.name!r}>"170+171 def _is_setup_finished(self):172 raise NotImplementedError173 174+ @property175+ def static_folder(self):176+ """The absolute path to the configured static folder. ``None``177+ if no static folder is set.178+ """179+ if self._static_folder is not None:180+ return os.path.join(self.root_path, self._static_folder)181+182+ @static_folder.setter183+ def static_folder(self, value):184+ if value is not None:185+ value = os.fspath(value).rstrip(r"\/")186+187+ self._static_folder = value188+189+ @property190+ def has_static_folder(self):191+ """``True`` if :attr:`static_folder` is set.192+193+ .. versionadded:: 0.5194+ """195+ return self.static_folder is not None196+197+ @property198+ def static_url_path(self):199+ """The URL prefix that the static route will be accessible from.200+201+ If it was not configured during init, it is derived from202+ :attr:`static_folder`.203+ """204+ if self._static_url_path is not None:205+ return self._static_url_path206+207+ if self.static_folder is not None:208+ basename = os.path.basename(self.static_folder)209+ return f"/{basename}".rstrip("/")210+211+ @static_url_path.setter212+ def static_url_path(self, value):213+ if value is not None:214+ value = value.rstrip("/")215+216+ self._static_url_path = value217+218+ def get_send_file_max_age(self, filename):219+ """Used by :func:`send_file` to determine the ``max_age`` cache220+ value for a given file path if it wasn't passed.221+222+ By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from223+ the configuration of :data:`~flask.current_app`. This defaults224+ to ``None``, which tells the browser to use conditional requests225+ instead of a timed cache, which is usually preferable.226+227+ .. versionchanged:: 2.0228+ The default configuration is ``None`` instead of 12 hours.229+230+ .. versionadded:: 0.9231+ """232+ value = current_app.send_file_max_age_default233+234+ if value is None:235+ return None236+237+ return int(value.total_seconds())238+239+ def send_static_file(self, filename):240+ """The view function used to serve files from241+ :attr:`static_folder`. A route is automatically registered for242+ this view at :attr:`static_url_path` if :attr:`static_folder` is243+ set.244+245+ .. versionadded:: 0.5246+ """247+ if not self.has_static_folder:248+ raise RuntimeError("'static_folder' must be set to serve static_files.")249+250+ # send_file only knows to call get_send_file_max_age on the app,251+ # call it here so it works for blueprints too.252+ max_age = self.get_send_file_max_age(filename)253+ return send_from_directory(self.static_folder, filename, max_age=max_age)254+255+ @locked_cached_property256+ def jinja_loader(self):257+ """The Jinja loader for this object's templates. By default this258+ is a class :class:`jinja2.loaders.FileSystemLoader` to259+ :attr:`template_folder` if it is set.260+261+ .. versionadded:: 0.5262+ """263+ if self.template_folder is not None:264+ return FileSystemLoader(os.path.join(self.root_path, self.template_folder))265+266+ def open_resource(self, resource, mode="rb"):267+ """Open a resource file relative to :attr:`root_path` for268+ reading.269+270+ For example, if the file ``schema.sql`` is next to the file271+ ``app.py`` where the ``Flask`` app is defined, it can be opened272+ with:273+274+ .. code-block:: python275+276+ with app.open_resource("schema.sql") as f:277+ conn.executescript(f.read())278+279+ :param resource: Path to the resource relative to280+ :attr:`root_path`.281+ :param mode: Open the file in this mode. Only reading is282+ supported, valid values are "r" (or "rt") and "rb".283+ """284+ if mode not in {"r", "rt", "rb"}:285+ raise ValueError("Resources can only be opened for reading.")286+287+ return open(os.path.join(self.root_path, resource), mode)288+289 def _method_route(self, method, rule, options):290 if "methods" in options:291 raise TypeError("Use the 'route' decorator to use the 'methods' argument.")292 35 unmodified lines328 return self._method_route("PATCH", rule, options)329 330 def route(self, rule, **options):331 """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::332+ given URL rule. This does the same thing as :meth:`add_url_rule`333+ but is used as a decorator. See :meth:`add_url_rule` and334+ :ref:`url-route-registrations` for more information.335 336+ .. code-block:: python337+198- @app.route('/')338+ @app.route("/")339 def index():200- return 'Hello World'340+ return "Hello World"341 202- For more information refer to :ref:`url-route-registrations`.203-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 change342+ :param rule: The URL rule as a string.343+ :param options: The options to be forwarded to the underlying344+ :class:`~werkzeug.routing.Rule` object.210- 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.345 """346 347 def decorator(f):348 endpoint = options.pop("endpoint", None)230 unmodified lines579 function. This always is the function name.580 """581 assert view_func is not None, "expected view func if endpoint is not provided."582 return view_func.__name__583+584+585+def get_root_path(import_name):586+ """Find the root path of a package, or the path that contains a587+ module. If it cannot be found, returns the current working588+ directory.589+590+ Not to be confused with the value returned by :func:`find_package`.591+592+ :meta private:593+ """594+ # Module already imported and has a file attribute. Use that first.595+ mod = sys.modules.get(import_name)596+597+ if mod is not None and hasattr(mod, "__file__"):598+ return os.path.dirname(os.path.abspath(mod.__file__))599+600+ # Next attempt: check the loader.601+ loader = pkgutil.get_loader(import_name)602+603+ # Loader does not exist or we're referring to an unloaded main604+ # module or a main module without path (interactive sessions), go605+ # with the current working directory.606+ if loader is None or import_name == "__main__":607+ return os.getcwd()608+609+ if hasattr(loader, "get_filename"):610+ filepath = loader.get_filename(import_name)611+ else:612+ # Fall back to imports.613+ __import__(import_name)614+ mod = sys.modules[import_name]615+ filepath = getattr(mod, "__file__", None)616+617+ # If we don't have a file path it might be because it is a618+ # namespace package. In this case pick the root path from the619+ # first module that is contained in the package.620+ if filepath is None:621+ raise RuntimeError(622+ "No root path can be found for the provided module"623+ f" {import_name!r}. This can happen because the module"624+ " came from an import hook that does not provide file"625+ " name information or because it's a namespace package."626+ " In this case the root path needs to be explicitly"627+ " provided."628+ )629+630+ # filepath is import_name.py for a module, or __init__.py for a package.631+ return os.path.dirname(os.path.abspath(filepath))632+633+634+def _matching_loader_thinks_module_is_package(loader, mod_name):635+ """Attempt to figure out if the given name is a package or a module.636+637+ :param: loader: The loader that handled the name.638+ :param mod_name: The name of the package or module.639+ """640+ # Use loader.is_package if it's available.641+ if hasattr(loader, "is_package"):642+ return loader.is_package(mod_name)643+644+ cls = type(loader)645+646+ # NamespaceLoader doesn't implement is_package, but all names it647+ # loads must be packages.648+ if cls.__module__ == "_frozen_importlib" and cls.__name__ == "NamespaceLoader":649+ return True650+651+ # Otherwise we need to fail with an error that explains what went652+ # wrong.653+ raise AttributeError(654+ f"'{cls.__name__}.is_package()' must be implemented for PEP 302"655+ f" import hooks."656+ )657+658+659+def _find_package_path(root_mod_name):660+ """Find the path that contains the package or module."""661+ try:662+ spec = importlib.util.find_spec(root_mod_name)663+664+ if spec is None:665+ raise ValueError("not found")666+ # ImportError: the machinery told us it does not exist667+ # ValueError:668+ # - the module name was invalid669+ # - the module name is __main__670+ # - *we* raised `ValueError` due to `spec` being `None`671+ except (ImportError, ValueError):672+ pass # handled below673+ else:674+ # namespace package675+ if spec.origin in {"namespace", None}:676+ return os.path.dirname(next(iter(spec.submodule_search_locations)))677+ # a package (with __init__.py)678+ elif spec.submodule_search_locations:679+ return os.path.dirname(os.path.dirname(spec.origin))680+ # just a normal module681+ else:682+ return os.path.dirname(spec.origin)683+684+ # we were unable to find the `package_path` using PEP 451 loaders685+ loader = pkgutil.get_loader(root_mod_name)686+687+ if loader is None or root_mod_name == "__main__":688+ # import name is not found, or interactive/main module689+ return os.getcwd()690+691+ if hasattr(loader, "get_filename"):692+ filename = loader.get_filename(root_mod_name)693+ elif hasattr(loader, "archive"):694+ # zipimporter's loader.archive points to the .egg or .zip file.695+ filename = loader.archive696+ else:697+ # At least one loader is missing both get_filename and archive:698+ # Google App Engine's HardenedModulesHook, use __file__.699+ filename = importlib.import_module(root_mod_name).__file__700+701+ package_path = os.path.abspath(os.path.dirname(filename))702+703+ # If the imported name is a package, filename is currently pointing704+ # to the root of the package, need to get the current directory.705+ if _matching_loader_thinks_module_is_package(loader, root_mod_name):706+ package_path = os.path.dirname(package_path)707+708+ return package_path709+710+711+def find_package(import_name):712+ """Find the prefix that a package is installed under, and the path713+ that it would be imported from.714+715+ The prefix is the directory containing the standard directory716+ hierarchy (lib, bin, etc.). If the package is not installed to the717+ system (:attr:`sys.prefix`) or a virtualenv (``site-packages``),718+ ``None`` is returned.719+720+ The path is the entry in :attr:`sys.path` that contains the package721+ for import. If the package is not installed, it's assumed that the722+ package was imported from the current working directory.723+ """724+ root_mod_name, _, _ = import_name.partition(".")725+ package_path = _find_package_path(root_mod_name)726+ py_prefix = os.path.abspath(sys.prefix)727+728+ # installed to the system729+ if package_path.startswith(py_prefix):730+ return py_prefix, package_path731+732+ site_parent, site_folder = os.path.split(package_path)733+734+ # installed to a virtualenv735+ if site_folder.lower() == "site-packages":736+ parent, folder = os.path.split(site_parent)737+738+ # Windows (prefix/lib/site-packages)739+ if folder.lower() == "lib":740+ return parent, package_path741+742+ # Unix (prefix/lib/pythonX.Y/site-packages)743+ if os.path.basename(parent).lower() == "lib":744+ return os.path.dirname(parent), package_path745+746+ # something else (prefix/site-packages)747+ return site_parent, package_path748+749+ # not installed750+ return None, package_path