Skip to content

Commit 976973c

Browse files
committed
files: lookup resources via importlib if available
1 parent 5dd44f1 commit 976973c

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

glad/files/__init__.py

+16-9
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,19 @@
88
from urllib.parse import urlparse
99

1010
try:
11-
from pkg_resources import resource_exists, resource_stream
11+
from importlib.resources import files
12+
13+
def resource_open(package, name, *args, **kwargs):
14+
return files(package).joinpath(name).open(*args, **kwargs)
1215
except ImportError:
13-
def resource_exists(*args, **kwargs):
14-
return False
16+
try:
17+
from pkg_resources import resource_stream
1518

16-
def resource_stream(*args, **kwargs):
17-
return None
19+
def resource_open(package, name, *args, **kwargs):
20+
return resource_stream(package, name)
21+
except ImportError:
22+
def resource_open(package, name, *args, **kwargs):
23+
raise FileNotFoundError
1824

1925

2026
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
@@ -29,12 +35,13 @@ class GladFileException(Exception):
2935
def open_local(name, *args, **kwargs):
3036
# use pkg_resources when available, makes it work in zipped modules
3137
# or other environments
32-
if resource_exists(__name__, name):
33-
logger.info('opening packaged resource: %r', name)
34-
return resource_stream(__name__, name)
38+
try:
39+
return resource_open(__name__, name, *args, **kwargs)
40+
except FileNotFoundError:
41+
pass
3542

3643
# fallback to filesystem
37-
logger.info('opening packaged path: %r', name)
44+
logger.info('falling back to packaged path: %r', name)
3845
local_path = os.path.normpath(os.path.join(BASE_PATH, os.path.join(name)))
3946
if not local_path.startswith(BASE_PATH):
4047
raise GladFileException('unsafe file path, won\'t open {!r}'.format(local_path))

0 commit comments

Comments
 (0)