Last active
September 9, 2018 02:45
-
-
Save dgnsrekt/30d2f444e9cad3b2072e0d25c5a7f3e7 to your computer and use it in GitHub Desktop.
A python configuration concept.
This file contains hidden or 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
import toml | |
import structlog | |
from pathlib import Path | |
class InvalidSettingError(ValueError): | |
pass | |
class ConfigurationBase: | |
DEFAULT_CONFIG = dict() | |
def __init__(self, subclass, **kwargs): | |
self.key = subclass.__class__.__name__ | |
self.value = kwargs | |
ConfigurationBase.DEFAULT_CONFIG[self.key] = self.value | |
def __repr__(self): | |
return f'{self.key}: {self.value}' | |
class Server(ConfigurationBase): | |
def __init__(self, **kwargs): | |
super().__init__(self, **kwargs) | |
class Client(ConfigurationBase): | |
def __init__(self, **kwargs): | |
super().__init__(self, **kwargs) | |
class General(ConfigurationBase): | |
def __init__(self, **kwargs): | |
super().__init__(self, **kwargs) | |
class Configuration: | |
Server(Port='6666', Ip='192.168.50.11') | |
Client(Port='6666', Ip='192.168.50.12') | |
General(DEBUG_MODE=True) | |
CONFIG_DEFAULT = ConfigurationBase.DEFAULT_CONFIG | |
_PATH = Path(__file__).parent / 'config.toml' | |
logger = structlog.get_logger() | |
def __init__(self): | |
self.settings = None | |
self._load() | |
def _load(self): | |
if not Configuration._PATH.exists(): | |
self.logger.info('config.toml file not found.', path=Configuration._PATH) | |
self.write_clean_configuration_file() | |
self.settings = self._readfile() | |
self.logger.info('config.toml loaded.', path=Configuration._PATH) | |
for setting in self.settings: | |
self.logger.info(f'{setting} settings:', current=self[setting]) | |
def _readfile(cls): | |
with open(cls._PATH, 'r') as file: | |
return toml.loads(file.read()) | |
@classmethod | |
def write_clean_configuration_file(cls): | |
with open(cls._PATH, 'w') as file: | |
file.write(toml.dumps(cls.CONFIG_DEFAULT)) | |
cls.logger.info('writing clean config.toml file.', path=cls._PATH) | |
def __getitem__(self, section): | |
try: | |
return self.settings[section] | |
except KeyError as e: | |
raise InvalidSettingError(f'{section} is an invalid configuration key. ' | |
'Use the following configuration keys: ', list(self.settings.keys())) | |
def __repr__(self): | |
repr = '----CONFIGURATION----\n' | |
for key, value in self.settings.items(): | |
repr += f'{key}: {value}\n' | |
return repr | |
Configuration.write_clean_configuration_file() | |
config = Configuration() | |
print(config['Server']) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment