|
11 | 11 | from . import core |
12 | 12 | import warnings |
13 | 13 | from ..utils import ensure_path_exists |
14 | | -from pkg_resources import resource_filename |
15 | 14 | import json |
16 | 15 | from .utils import _ChainMap |
17 | 16 | from .handlers_base import DuplicateHandler |
|
20 | 19 | logger = logging.getLogger(__name__) |
21 | 20 |
|
22 | 21 |
|
| 22 | +@contextmanager |
| 23 | +def open_resource_file( |
| 24 | + package: str, # ModuleType |
| 25 | + resource: str, # os.PathLike |
| 26 | +): |
| 27 | + """Context manager to open a resource file. |
| 28 | +
|
| 29 | + Parameters |
| 30 | + ---------- |
| 31 | + package : str (ModuleType) |
| 32 | + The package containing the resource. |
| 33 | + resource : str (os.PathLike) |
| 34 | + The resource to open. |
| 35 | +
|
| 36 | + Yields |
| 37 | + ------ |
| 38 | + file : TextIO |
| 39 | + A text file-like object for the resource. |
| 40 | + """ |
| 41 | + use_importlib = True |
| 42 | + try: |
| 43 | + from importlib.resources import as_file, files |
| 44 | + except ImportError: # pragma: no cover |
| 45 | + try: |
| 46 | + from importlib_resources import as_file, files |
| 47 | + except ImportError: # pragma: no cover |
| 48 | + from pkg_resources import resource_filename |
| 49 | + use_importlib = False |
| 50 | + |
| 51 | + if use_importlib: |
| 52 | + with as_file(files(package) / resource) as path: |
| 53 | + with open(path, 'r', encoding='utf-8') as fin: |
| 54 | + yield fin |
| 55 | + else: |
| 56 | + path = resource_filename(package, resource) |
| 57 | + with open(path, 'r', encoding='utf-8') as fin: |
| 58 | + yield fin |
| 59 | + |
| 60 | + |
23 | 61 | class BaseRegistryRO(object): |
24 | 62 | """This is the base-class for asset registries. |
25 | 63 |
|
@@ -75,11 +113,9 @@ def DatumNotFound(self): |
75 | 113 | base_name = 'schemas/' |
76 | 114 | resource_name = '{}{}_resource.json'.format(base_name, spec_name) |
77 | 115 | datum_name = '{}{}_datum.json'.format(base_name, spec_name) |
78 | | - with open(resource_filename('databroker.assets', |
79 | | - resource_name), 'r') as fin: |
| 116 | + with open_resource_file('databroker.assets', resource_name) as fin: |
80 | 117 | tmp_dict['resource'] = json.load(fin) |
81 | | - with open(resource_filename('databroker.assets', |
82 | | - datum_name), 'r') as fin: |
| 118 | + with open_resource_file('databroker.assets', datum_name) as fin: |
83 | 119 | tmp_dict['datum'] = json.load(fin) |
84 | 120 | KNOWN_SPEC[spec_name] = tmp_dict |
85 | 121 |
|
|
0 commit comments