BW3-Core/boswatch/configYaml.py

78 lines
2.5 KiB
Python
Raw Permalink Normal View History

2019-02-27 08:02:40 +01:00
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""!
____ ____ ______ __ __ __ _____
/ __ )/ __ \/ ___/ | / /___ _/ /______/ /_ |__ /
/ __ / / / /\__ \| | /| / / __ `/ __/ ___/ __ \ /_ <
/ /_/ / /_/ /___/ /| |/ |/ / /_/ / /_/ /__/ / / / ___/ /
/_____/\____//____/ |__/|__/\__,_/\__/\___/_/ /_/ /____/
German BOS Information Script
by Bastian Schroll
2019-02-27 08:39:54 +01:00
@file: configYaml.py
2019-02-27 08:02:40 +01:00
@date: 27.02.2019
@author: Bastian Schroll
@description: Module for the configuration in YAML format
2019-02-27 08:02:40 +01:00
"""
import logging
import yaml
2019-03-03 13:32:31 +01:00
import yaml.parser
2019-02-27 08:02:40 +01:00
logging.debug("- %s loaded", __name__)
class ConfigYAML:
def __init__(self, config=None):
2019-03-01 22:12:29 +01:00
self._config = config
def __iter__(self):
2019-03-01 22:12:29 +01:00
for item in self._config:
if type(item) is list or type(item) is dict:
yield ConfigYAML(item)
else:
yield item
2019-10-26 13:41:17 +02:00
def __len__(self):
"""!returns the length of an config element"""
return len(self._config)
def __str__(self):
2019-03-11 07:47:51 +01:00
"""!Returns the string representation of the internal config dict"""
2019-03-01 22:12:29 +01:00
return str(self._config)
def loadConfigFile(self, configPath):
2019-03-02 09:15:40 +01:00
"""!loads a given configuration file
@param configPath: Path to the config file
@return True or False"""
logging.debug("load config file from: %s", configPath)
try:
with open(configPath) as file:
# use safe_load instead load
2019-03-01 22:12:29 +01:00
self._config = yaml.safe_load(file)
return True
2019-03-03 13:32:31 +01:00
except FileNotFoundError:
logging.error("config file not found: %s", configPath)
except yaml.parser.ParserError:
logging.exception("syntax error in config file: %s", configPath)
2019-03-03 13:32:31 +01:00
return False
def get(self, *args, default=None):
2019-03-11 07:47:51 +01:00
"""!Get a single value from the config
or a value set in a new configYAML class instance
@param *args: Config section (one ore more strings)
@param default: Default value if section not found (None)
@return: A single value, a value set in an configYAML instance, the default value"""
2019-03-01 22:12:29 +01:00
tmp = self._config
try:
for arg in args:
tmp = tmp.get(arg, default)
if type(tmp) is list or type(tmp) is dict:
return ConfigYAML(tmp)
else:
return tmp
2019-10-21 11:22:53 +02:00
except AttributeError: # pragma: no cover
return default