| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- from __future__ import absolute_import
- from __future__ import unicode_literals
- import logging
- import os
- from .errors import ConfigurationError
- log = logging.getLogger(__name__)
- class BlankDefaultDict(dict):
- def __init__(self, *args, **kwargs):
- super(BlankDefaultDict, self).__init__(*args, **kwargs)
- self.missing_keys = []
- def __getitem__(self, key):
- try:
- return super(BlankDefaultDict, self).__getitem__(key)
- except KeyError:
- if key not in self.missing_keys:
- log.warn(
- "The {} variable is not set. Defaulting to a blank string."
- .format(key)
- )
- self.missing_keys.append(key)
- return ""
- class Environment(BlankDefaultDict):
- __instance = None
- @classmethod
- def get_instance(cls, base_dir='.'):
- if cls.__instance:
- return cls.__instance
- instance = cls(base_dir)
- cls.__instance = instance
- return instance
- @classmethod
- def reset(cls):
- cls.__instance = None
- def __init__(self, base_dir):
- super(Environment, self).__init__()
- self.load_environment_file(os.path.join(base_dir, '.env'))
- self.update(os.environ)
- def load_environment_file(self, path):
- if not os.path.exists(path):
- return
- mapping = {}
- with open(path, 'r') as f:
- for line in f.readlines():
- line = line.strip()
- if '=' not in line:
- raise ConfigurationError(
- 'Invalid environment variable mapping in env file. '
- 'Missing "=" in "{0}"'.format(line)
- )
- mapping.__setitem__(*line.split('=', 1))
- self.update(mapping)
- def get_instance(base_dir=None):
- return Environment.get_instance(base_dir)
|