Skip to content

Commit a9ab4b3

Browse files
authored
Use resources loader to handle non-filesystem situations (#120)
* Use a resources loader if possible * Remove logic duplication
1 parent d15edfc commit a9ab4b3

File tree

1 file changed

+27
-12
lines changed

1 file changed

+27
-12
lines changed

certifi/core.py

+27-12
Original file line numberDiff line numberDiff line change
@@ -6,25 +6,40 @@
66
77
This module returns the installation location of cacert.pem or its contents.
88
"""
9+
import importlib
910
import os
1011

1112
try:
12-
from importlib.resources import read_text
13+
import importlib.resources
14+
# Defeat lazy module importers.
15+
importlib.resources.open_binary
16+
_HAVE_RESOURCE_READER = True
1317
except ImportError:
14-
# This fallback will work for Python versions prior to 3.7 that lack the
15-
# importlib.resources module but relies on the existing `where` function
16-
# so won't address issues with environments like PyOxidizer that don't set
17-
# __file__ on modules.
18-
def read_text(_module, _path, encoding="ascii"):
19-
with open(where(), "r", encoding=encoding) as data:
20-
return data.read()
18+
_HAVE_RESOURCE_READER = False
2119

20+
try:
21+
import pkg_resources
22+
# Defeat lazy module importers.
23+
_HAVE_PKG_RESOURCES = True
24+
except ImportError:
25+
_HAVE_PKG_RESOURCES = False
2226

23-
def where():
24-
f = os.path.dirname(__file__)
27+
_PACKAGE_NAME = "certifi"
28+
_CACERT_NAME = "cacert.pem"
2529

26-
return os.path.join(f, "cacert.pem")
30+
31+
def where():
32+
if _HAVE_PKG_RESOURCES:
33+
return pkg_resources.resource_filename(_PACKAGE_NAME, _CACERT_NAME)
34+
else:
35+
mod = importlib.import_module(_PACKAGE_NAME)
36+
path = os.path.dirname(mod.__file__)
37+
return os.path.join(path, _CACERT_NAME)
2738

2839

2940
def contents():
30-
return read_text("certifi", "cacert.pem", encoding="ascii")
41+
if _HAVE_RESOURCE_READER:
42+
return importlib.resources.read_text(_PACKAGE_NAME, _CACERT_NAME, encoding="ascii")
43+
else:
44+
with open(where(), "r", encoding="ascii") as data:
45+
return data.read()

0 commit comments

Comments
 (0)