Skip to content

Commit 3fc8fec

Browse files
authored
Fix where() so that it works with importlib.resources when available (#123)
1 parent 5efdd48 commit 3fc8fec

File tree

1 file changed

+35
-5
lines changed

1 file changed

+35
-5
lines changed

certifi/core.py

+35-5
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,36 @@
99
import os
1010

1111
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+
1342
except ImportError:
1443
# This fallback will work for Python versions prior to 3.7 that lack the
1544
# importlib.resources module but relies on the existing `where` function
@@ -19,11 +48,12 @@ def read_text(_module, _path, encoding="ascii"):
1948
with open(where(), "r", encoding=encoding) as data:
2049
return data.read()
2150

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__)
2255

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")
2757

2858

2959
def contents():

0 commit comments

Comments
 (0)