9
9
import os
10
10
11
11
try :
12
- from importlib .resources import read_text
12
+ from importlib .resources import path as get_path , read_text
13
+
14
+ _CACERT_CTX = None
15
+ _CACERT_PATH = None
16
+
17
+ def where ():
18
+ # This is slightly terrible, but we want to delay extracting the file
19
+ # in cases where we're inside of a zipimport situation until someone
20
+ # actually calls where(), but we don't want to re-extract the file
21
+ # on every call of where(), so we'll do it once then store it in a
22
+ # global variable.
23
+ global _CACERT_CTX
24
+ global _CACERT_PATH
25
+ if _CACERT_PATH is None :
26
+ # This is slightly janky, the importlib.resources API wants you to
27
+ # manage the cleanup of this file, so it doesn't actually return a
28
+ # path, it returns a context manager that will give you the path
29
+ # when you enter it and will do any cleanup when you leave it. In
30
+ # the common case of not needing a temporary file, it will just
31
+ # return the file system location and the __exit__() is a no-op.
32
+ #
33
+ # We also have to hold onto the actual context manager, because
34
+ # it will do the cleanup whenever it gets garbage collected, so
35
+ # we will also store that at the global level as well.
36
+ _CACERT_CTX = get_path ("certifi" , "cacert.pem" )
37
+ _CACERT_PATH = str (_CACERT_CTX .__enter__ ())
38
+
39
+ return _CACERT_PATH
40
+
41
+
13
42
except ImportError :
14
43
# This fallback will work for Python versions prior to 3.7 that lack the
15
44
# importlib.resources module but relies on the existing `where` function
@@ -19,11 +48,12 @@ def read_text(_module, _path, encoding="ascii"):
19
48
with open (where (), "r" , encoding = encoding ) as data :
20
49
return data .read ()
21
50
51
+ # If we don't have importlib.resources, then we will just do the old logic
52
+ # of assuming we're on the filesystem and munge the path directly.
53
+ def where ():
54
+ f = os .path .dirname (__file__ )
22
55
23
- def where ():
24
- f = os .path .dirname (__file__ )
25
-
26
- return os .path .join (f , "cacert.pem" )
56
+ return os .path .join (f , "cacert.pem" )
27
57
28
58
29
59
def contents ():
0 commit comments