environment.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import logging
  4. import os
  5. from .errors import ConfigurationError
  6. log = logging.getLogger(__name__)
  7. class BlankDefaultDict(dict):
  8. def __init__(self, *args, **kwargs):
  9. super(BlankDefaultDict, self).__init__(*args, **kwargs)
  10. self.missing_keys = []
  11. def __getitem__(self, key):
  12. try:
  13. return super(BlankDefaultDict, self).__getitem__(key)
  14. except KeyError:
  15. if key not in self.missing_keys:
  16. log.warn(
  17. "The {} variable is not set. Defaulting to a blank string."
  18. .format(key)
  19. )
  20. self.missing_keys.append(key)
  21. return ""
  22. class Environment(BlankDefaultDict):
  23. def __init__(self, base_dir):
  24. super(Environment, self).__init__()
  25. if base_dir:
  26. self.load_environment_file(os.path.join(base_dir, '.env'))
  27. self.update(os.environ)
  28. def load_environment_file(self, path):
  29. if not os.path.exists(path):
  30. return
  31. mapping = {}
  32. with open(path, 'r') as f:
  33. for line in f.readlines():
  34. line = line.strip()
  35. if '=' not in line:
  36. raise ConfigurationError(
  37. 'Invalid environment variable mapping in env file. '
  38. 'Missing "=" in "{0}"'.format(line)
  39. )
  40. mapping.__setitem__(*line.split('=', 1))
  41. self.update(mapping)