8
8
from urllib .parse import urlparse
9
9
10
10
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 )
12
15
except ImportError :
13
- def resource_exists ( * args , ** kwargs ) :
14
- return False
16
+ try :
17
+ from pkg_resources import resource_stream
15
18
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
18
24
19
25
20
26
BASE_PATH = os .path .abspath (os .path .dirname (__file__ ))
@@ -29,12 +35,13 @@ class GladFileException(Exception):
29
35
def open_local (name , * args , ** kwargs ):
30
36
# use pkg_resources when available, makes it work in zipped modules
31
37
# 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
35
42
36
43
# fallback to filesystem
37
- logger .info ('opening packaged path: %r' , name )
44
+ logger .info ('falling back to packaged path: %r' , name )
38
45
local_path = os .path .normpath (os .path .join (BASE_PATH , os .path .join (name )))
39
46
if not local_path .startswith (BASE_PATH ):
40
47
raise GladFileException ('unsafe file path, won\' t open {!r}' .format (local_path ))
0 commit comments