diff options
author | Federico Ceratto <federico.ceratto@gmail.com> | 2017-12-19 23:39:27 +0000 |
---|---|---|
committer | Federico Ceratto <federico.ceratto@gmail.com> | 2017-12-19 23:39:27 +0000 |
commit | 6abdfdead1326ccca98dc4cf415c216f1bf25400 (patch) | |
tree | 70b803bd499fd45e89627c1b45b90ddf20e8e959 /python.d/python_modules/bases/loaders.py | |
parent | Release v. 1.8.0+dfsg-1 to Unstable (diff) | |
parent | New upstream version 1.9.0+dfsg (diff) | |
download | netdata-6abdfdead1326ccca98dc4cf415c216f1bf25400.tar.xz netdata-6abdfdead1326ccca98dc4cf415c216f1bf25400.zip |
Update upstream source from tag 'upstream/1.9.0+dfsg'
Update to upstream version '1.9.0+dfsg'
with Debian dir 28b8242a05f9ad26cd1cdbcf078be754fc7d6251
Diffstat (limited to 'python.d/python_modules/bases/loaders.py')
-rw-r--r-- | python.d/python_modules/bases/loaders.py | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/python.d/python_modules/bases/loaders.py b/python.d/python_modules/bases/loaders.py new file mode 100644 index 000000000..d18b9dcd0 --- /dev/null +++ b/python.d/python_modules/bases/loaders.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +# Description: +# Author: Ilya Mashchenko (l2isbad) + +import types +from sys import version_info + +PY_VERSION = version_info[:2] + +if PY_VERSION > (3, 1): + from pyyaml3 import SafeLoader as YamlSafeLoader + from importlib.machinery import SourceFileLoader + DEFAULT_MAPPING_TAG = 'tag:yaml.org,2002:map' +else: + from pyyaml2 import SafeLoader as YamlSafeLoader + from imp import load_source as SourceFileLoader + DEFAULT_MAPPING_TAG = u'tag:yaml.org,2002:map' + +try: + from collections import OrderedDict +except ImportError: + from third_party.ordereddict import OrderedDict + + +def dict_constructor(loader, node): + return OrderedDict(loader.construct_pairs(node)) + + +YamlSafeLoader.add_constructor(DEFAULT_MAPPING_TAG, dict_constructor) + + +class YamlOrderedLoader: + @staticmethod + def load_config_from_file(file_name): + opened, loaded = False, False + try: + stream = open(file_name, 'r') + opened = True + loader = YamlSafeLoader(stream) + loaded = True + parsed = loader.get_single_data() or dict() + except Exception as error: + return dict(), error + else: + return parsed, None + finally: + if opened: + stream.close() + if loaded: + loader.dispose() + + +class SourceLoader: + @staticmethod + def load_module_from_file(name, path): + try: + loaded = SourceFileLoader(name, path) + if isinstance(loaded, types.ModuleType): + return loaded, None + return loaded.load_module(), None + except Exception as error: + return None, error + + +class ModuleAndConfigLoader(YamlOrderedLoader, SourceLoader): + pass |