diff --git a/README.md b/README.md index 2006145..8a2f625 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,17 @@ If there's an environment variable with the same name as the given configuration # even if the default for 'SOMETHING' or the value in the config file is different from 'value' + +It's useful to use prefixes to make sure your project environment variables do not conflict with other projects's environment variables: + + from derpconf.config import Config + + Config.allow_environment_variables(prefix='MYAPP_') + + # called program with MYAPP_SOMETHING=value myprogram.py + assert config.SOMETHING == "value" + + Reloading Configurations ------------------------ diff --git a/derpconf/config.py b/derpconf/config.py index 831c8e6..b61a11e 100644 --- a/derpconf/config.py +++ b/derpconf/config.py @@ -32,6 +32,7 @@ class Config(object): class_aliases = defaultdict(list) class_aliased_items = {} _allow_environment_variables = False + _environment_variables_prefix = '' @classmethod def define(cls, key, value, description, group='General'): @@ -57,8 +58,9 @@ def get_conf_file(cls, conf_name, lookup_paths): return None @classmethod - def allow_environment_variables(cls): + def allow_environment_variables(cls, prefix=''): cls._allow_environment_variables = True + cls._environment_variables_prefix = prefix @classmethod def load(cls, path, conf_name=None, lookup_paths=[], defaults={}): @@ -171,11 +173,12 @@ def __setattr__(self, name, value): super(Config, self).__setattr__(name, value) def __getattribute__(self, name): - if name in ['allow_environment_variables']: + if name in ['allow_environment_variables', '_environment_variables_prefix']: return super(Config, self).__getattribute__(name) if self.allow_environment_variables: - value = os.environ.get(name, None) + prefix = self._environment_variables_prefix + value = os.environ.get(prefix + name, None) if value is not None: return value diff --git a/vows/config_vows.py b/vows/config_vows.py index 24e479c..0092288 100644 --- a/vows/config_vows.py +++ b/vows/config_vows.py @@ -183,6 +183,18 @@ def topic(self): def should_be_equal_to_env(self, topic): expect(topic).to_equal("baz") + class WhenPassingPrefix(Vows.Context): + def topic(self): + os.environ['MYPREFIX_SOME_CONFIGURATION'] = "test value" + config = Config() + + Config.allow_environment_variables(prefix='MYPREFIX_') + + return config.SOME_CONFIGURATION + + def should_be_equal_to_env(self, topic): + expect(topic).to_equal("test value") + class WhenReloading(Vows.Context): def topic(self): class SpecialConfig(Config):