|
6 | 6 |
|
7 | 7 | This module returns the installation location of cacert.pem or its contents.
|
8 | 8 | """
|
| 9 | +import importlib |
9 | 10 | import os
|
10 | 11 |
|
11 | 12 | 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 |
13 | 17 | 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 |
21 | 19 |
|
| 20 | +try: |
| 21 | + import pkg_resources |
| 22 | + # Defeat lazy module importers. |
| 23 | + _HAVE_PKG_RESOURCES = True |
| 24 | +except ImportError: |
| 25 | + _HAVE_PKG_RESOURCES = False |
22 | 26 |
|
23 |
| -def where(): |
24 |
| - f = os.path.dirname(__file__) |
| 27 | +_PACKAGE_NAME = "certifi" |
| 28 | +_CACERT_NAME = "cacert.pem" |
25 | 29 |
|
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) |
27 | 38 |
|
28 | 39 |
|
29 | 40 | 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