environment.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. __instance = None
  24. @classmethod
  25. def get_instance(cls, base_dir='.'):
  26. if cls.__instance:
  27. return cls.__instance
  28. instance = cls(base_dir)
  29. cls.__instance = instance
  30. return instance
  31. @classmethod
  32. def reset(cls):
  33. cls.__instance = None
  34. def __init__(self, base_dir):
  35. super(Environment, self).__init__()
  36. self.load_environment_file(os.path.join(base_dir, '.env'))
  37. self.update(os.environ)
  38. def load_environment_file(self, path):
  39. if not os.path.exists(path):
  40. return
  41. mapping = {}
  42. with open(path, 'r') as f:
  43. for line in f.readlines():
  44. line = line.strip()
  45. if '=' not in line:
  46. raise ConfigurationError(
  47. 'Invalid environment variable mapping in env file. '
  48. 'Missing "=" in "{0}"'.format(line)
  49. )
  50. mapping.__setitem__(*line.split('=', 1))
  51. self.update(mapping)
  52. def get_instance(base_dir=None):
  53. return Environment.get_instance(base_dir)