Skip to content
Myr

Merge pull request #4610 from eprigorodov/feature-4602-namespace-path

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 fb89745, b06df0a · Browse files · 4 files+59 added−27 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+59 added−27 removed

  • tests:+19 added−15 removed
  • other:+40 added−12 removed

4 files+59 added−27 removed

modified:src/flask/scaffold.py+37 added-12 removed
1import importlib.util2import os3import pathlib4import pkgutil5import sys6import typing as t7from collections import defaultdict
772 unmodified lines
780 f" import hooks."781 )782783784def _path_is_relative_to(path: pathlib.PurePath, base: str) -> bool:785 # Path.is_relative_to doesn't exist until Python 3.9786 try:787 path.relative_to(base)788 return True789 except ValueError:790 return False791792783def _find_package_path(root_mod_name):793def _find_package_path(import_name):794 """Find the path that contains the package or module."""795 root_mod_name, _, _ = import_name.partition(".")796797 try:786 spec = importlib.util.find_spec(root_mod_name)798 root_spec = importlib.util.find_spec(root_mod_name)799788 if spec is None:800 if root_spec is None:801 raise ValueError("not found")802 # ImportError: the machinery told us it does not exist803 # ValueError:804 # - the module name was invalid805 # - the module name is __main__794 # - *we* raised `ValueError` due to `spec` being `None`806 # - *we* raised `ValueError` due to `root_spec` being `None`807 except (ImportError, ValueError):808 pass # handled below809 else:810 # namespace package799 if spec.origin in {"namespace", None}:800 return os.path.dirname(next(iter(spec.submodule_search_locations)))811 if root_spec.origin in {"namespace", None}:812 package_spec = importlib.util.find_spec(import_name)813 if package_spec is not None and package_spec.submodule_search_locations:814 # Pick the path in the namespace that contains the submodule.815 package_path = pathlib.Path(816 os.path.commonpath(package_spec.submodule_search_locations)817 )818 search_locations = (819 location820 for location in root_spec.submodule_search_locations821 if _path_is_relative_to(package_path, location)822 )823 else:824 # Pick the first path.825 search_locations = iter(root_spec.submodule_search_locations)826 return os.path.dirname(next(search_locations))827 # a package (with __init__.py)802 elif spec.submodule_search_locations:803 return os.path.dirname(os.path.dirname(spec.origin))828 elif root_spec.submodule_search_locations:829 return os.path.dirname(os.path.dirname(root_spec.origin))830 # just a normal module831 else:806 return os.path.dirname(spec.origin)832 return os.path.dirname(root_spec.origin)833834 # we were unable to find the `package_path` using PEP 451 loaders835 loader = pkgutil.get_loader(root_mod_name)836
33 unmodified lines
870 The path is the entry in :attr:`sys.path` that contains the package871 for import. If the package is not installed, it's assumed that the872 package was imported from the current working directory.873 """848 root_mod_name, _, _ = import_name.partition(".")849 package_path = _find_package_path(root_mod_name)874 package_path = _find_package_path(import_name)875 py_prefix = os.path.abspath(sys.prefix)876877 # installed to the system853 if package_path.startswith(py_prefix):878 if _path_is_relative_to(pathlib.PurePath(package_path), py_prefix):879 return py_prefix, package_path880881 site_parent, site_folder = os.path.split(package_path)882
17 unmodified lines
modified:tests/test_instance_config.py+19 added-15 removed
1import os1import sys23import pytest4
8 unmodified lines
13 app = flask.Flask(__name__, instance_path=str(modules_tmpdir))14 assert app.instance_path == str(modules_tmpdir)151618@pytest.mark.xfail(reason="weird interaction with tox")19def test_main_module_paths(modules_tmpdir, purge_module):20 app = modules_tmpdir.join("main_app.py")21 app.write('import flask\n\napp = flask.Flask("__main__")')22 purge_module("main_app")2324 from main_app import app2526 here = os.path.abspath(os.getcwd())27 assert app.instance_path == os.path.join(here, "instance")282930@pytest.mark.xfail(reason="weird interaction with tox")17def test_uninstalled_module_paths(modules_tmpdir, purge_module):18 app = modules_tmpdir.join("config_module_app.py").write(19 "import os\n"20 "import flask\n"
6 unmodified lines
2728 assert app.instance_path == str(modules_tmpdir.join("instance"))293045@pytest.mark.xfail(reason="weird interaction with tox")31def test_uninstalled_package_paths(modules_tmpdir, purge_module):32 app = modules_tmpdir.mkdir("config_package_app")33 init = app.join("__init__.py")34 init.write(
8 unmodified lines
4344 assert app.instance_path == str(modules_tmpdir.join("instance"))454647def test_uninstalled_namespace_paths(tmpdir, monkeypatch, purge_module):48 def create_namespace(package):49 project = tmpdir.join(f"project-{package}")50 monkeypatch.syspath_prepend(str(project))51 project.join("namespace").join(package).join("__init__.py").write(52 "import flask\napp = flask.Flask(__name__)\n", ensure=True53 )54 return project5556 _ = create_namespace("package1")57 project2 = create_namespace("package2")58 purge_module("namespace.package2")59 purge_module("namespace")6061 from namespace.package2 import app6263 assert app.instance_path == str(project2.join("instance"))646566def test_installed_module_paths(67 modules_tmpdir, modules_tmpdir_prefix, purge_module, site_packages, limit_loader68):69 site_packages.join("site_app.py").write(
56 unmodified lines
modified:CHANGES.rst+2 added
6 unmodified lines
78- Inline some optional imports that are only used for certain CLI9 commands. :pr:`4606`10- Relax type annotation for ``after_request`` functions. :issue:`4600`11- ``instance_path`` for namespace packages uses the path closest to12 the imported submodule. :issue:`4600`131415Version 2.1.216-------------
1280 unmodified lines
modified:tox.ini+1 added
7 unmodified lines
8 docs9skip_missing_interpreters = true1011[testenv]12envtmpdir = {toxworkdir}/tmp/{envname}13deps =14 -r requirements/tests.txt15 min: -r requirements/tests-pallets-min.txt16 dev: -r requirements/tests-pallets-dev.txt
18 unmodified lines