Source code for gemstone.config.configurator

import abc
import argparse


[docs]class BaseConfigurator(abc.ABC): """ Base class for defining configurators. A configurator is a class that, starting from a set of name-configurable pairs, depending on the configurables' options and the environment, builds a configuration for the application. """ def __init__(self): self.configurables = [] @abc.abstractmethod
[docs] def load(self): """ Loads the configuration for the application """ pass
@abc.abstractmethod
[docs] def get(self, name): """ Gets the extracted value for the specified name, if available. If no value could be loaded for the specified name, ``None`` must be returned. """ pass
[docs] def register_configurable(self, configurable): """ Registers a configurable instance with this configurator :param configurable: a :py:class:`Configurable` instance """ self.configurables.append(configurable)
[docs] def get_configurable_by_name(self, name): """ Returns the registered configurable with the specified name or ``None`` if no such configurator exists. """ l = [c for c in self.configurables if c.name == name] if l: return l[0]
def __repr__(self): return "<{}>".format(self.__class__.__name__) def __str__(self): return repr(self)
[docs]class CommandLineConfigurator(BaseConfigurator): """ Configurator that collects values from command line arguments. For each registered configurable, will attempt to get from command line the value designated by the argument ``--name`` where ``name`` is the name of the configurable. Example For the configurables - Configurable("a") - Configurable("b") - Configurable("c") the following command line interface will be exposed :: usage: service.py [-h] [--a A] [--b B] [--c C] optional arguments: -h, --help show this help message and exit --a A --b B --c C The ``service.py`` can be called like this :: python service.py --a=1 --b=2 --c=3 """ def __init__(self): super(CommandLineConfigurator, self).__init__() self.args = None def load(self): parser = argparse.ArgumentParser() for configurable in self.configurables: parser.add_argument("--" + configurable.name) self.args = parser.parse_args() def get(self, name): configurable = self.get_configurable_by_name(name) if not configurable: return None value = getattr(self.args, name, None) if not value: return None configurable.set_value(value) return configurable.get_final_value()