Last active
June 4, 2021 00:48
-
-
Save IlluminatiFish/5c85e3876398e01e9f4f69f6562d0c75 to your computer and use it in GitHub Desktop.
A short utility to use YAML configurations in Python and access their node data using the node1.node2.node3 format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# This program is a utility used by myself that I have released | |
# to the public under the GPLv3 license | |
# | |
# Copyright (c) 2021 IlluminatiFish. | |
# | |
# This program is free software: you can redistribute it and/or modify | |
# it under the terms of the GNU General Public License as published by | |
# the Free Software Foundation, version 3. | |
# | |
# This program is distributed in the hope that it will be useful, but | |
# WITHOUT ANY WARRANTY; without even the implied warranty of | |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | |
# General Public License for more details. | |
# | |
# You should have received a copy of the GNU General Public License | |
# along with this program. If not, see http://www.gnu.org/licenses/. | |
# | |
import yaml | |
import munch | |
import operator | |
class InvalidNodeException(Exception): | |
pass | |
class ParserException(Exception): | |
pass | |
def get_config_node(file, path): | |
if not file.endswith('.yml') and not file.endswith('.yaml'): | |
raise ParserException(f'Could not open {file} because is not a YAML file') | |
config_file = open(file, 'r') | |
try: | |
config_file_dict = yaml.safe_load(config_file.read()) | |
except yaml.parser.ParserError: | |
raise ParserException('Could not parse and load YAML configuration') | |
# Pass the YAML loaded dictionary into the Munch module | |
# So that is can return a class object so we can access | |
# the YAML's config nodes (and the dictionaries' keys) | |
munchified_config = munch.munchify(config_file_dict) | |
# Use the operator module to convert a string YAML node | |
# path into a python class attribute so that we can use | |
# it with our munchified configuration and retrieve the | |
# data from the node passed as @param path | |
try: | |
node_data = operator.attrgetter(path)(munchified_config) | |
except AttributeError: | |
raise InvalidNodeException('Invalid node path, the final node does not exist!') | |
# We get a Munch object returned if the @param path is | |
# not the full path to a valid node with data | |
if isinstance(node_data, munch.Munch): | |
raise InvalidNodeException('Invalid node path, please use a path that is the full node path to the data') | |
if node_data is not None: | |
return node_data | |
else: | |
raise InvalidNodeException(f'Invalid node data, there was no data found at your node path ({path})') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment