environment.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import codecs
  4. import contextlib
  5. import logging
  6. import os
  7. import re
  8. import six
  9. from ..const import IS_WINDOWS_PLATFORM
  10. from .errors import ConfigurationError
  11. from .errors import EnvFileNotFound
  12. log = logging.getLogger(__name__)
  13. def split_env(env):
  14. if isinstance(env, six.binary_type):
  15. env = env.decode('utf-8', 'replace')
  16. key = value = None
  17. if '=' in env:
  18. key, value = env.split('=', 1)
  19. else:
  20. key = env
  21. if re.search(r'\s', key):
  22. raise ConfigurationError(
  23. "environment variable name '{}' may not contains whitespace.".format(key)
  24. )
  25. return key, value
  26. def env_vars_from_file(filename):
  27. """
  28. Read in a line delimited file of environment variables.
  29. """
  30. if not os.path.exists(filename):
  31. raise EnvFileNotFound("Couldn't find env file: {}".format(filename))
  32. elif not os.path.isfile(filename):
  33. raise EnvFileNotFound("{} is not a file.".format(filename))
  34. env = {}
  35. with contextlib.closing(codecs.open(filename, 'r', 'utf-8-sig')) as fileobj:
  36. for line in fileobj:
  37. line = line.strip()
  38. if line and not line.startswith('#'):
  39. try:
  40. k, v = split_env(line)
  41. env[k] = v
  42. except ConfigurationError as e:
  43. raise ConfigurationError('In file {}: {}'.format(filename, e.msg))
  44. return env
  45. class Environment(dict):
  46. def __init__(self, *args, **kwargs):
  47. super(Environment, self).__init__(*args, **kwargs)
  48. self.missing_keys = []
  49. @classmethod
  50. def from_env_file(cls, base_dir):
  51. def _initialize():
  52. result = cls()
  53. if base_dir is None:
  54. return result
  55. env_file_path = os.path.join(base_dir, '.env')
  56. try:
  57. return cls(env_vars_from_file(env_file_path))
  58. except EnvFileNotFound:
  59. pass
  60. return result
  61. instance = _initialize()
  62. instance.update(os.environ)
  63. return instance
  64. @classmethod
  65. def from_command_line(cls, parsed_env_opts):
  66. result = cls()
  67. for k, v in parsed_env_opts.items():
  68. # Values from the command line take priority, unless they're unset
  69. # in which case they take the value from the system's environment
  70. if v is None and k in os.environ:
  71. result[k] = os.environ[k]
  72. else:
  73. result[k] = v
  74. return result
  75. def __getitem__(self, key):
  76. try:
  77. return super(Environment, self).__getitem__(key)
  78. except KeyError:
  79. if IS_WINDOWS_PLATFORM:
  80. try:
  81. return super(Environment, self).__getitem__(key.upper())
  82. except KeyError:
  83. pass
  84. if key not in self.missing_keys:
  85. log.warn(
  86. "The {} variable is not set. Defaulting to a blank string."
  87. .format(key)
  88. )
  89. self.missing_keys.append(key)
  90. return ""
  91. def __contains__(self, key):
  92. result = super(Environment, self).__contains__(key)
  93. if IS_WINDOWS_PLATFORM:
  94. return (
  95. result or super(Environment, self).__contains__(key.upper())
  96. )
  97. return result
  98. def get(self, key, *args, **kwargs):
  99. if IS_WINDOWS_PLATFORM:
  100. return super(Environment, self).get(
  101. key,
  102. super(Environment, self).get(key.upper(), *args, **kwargs)
  103. )
  104. return super(Environment, self).get(key, *args, **kwargs)
  105. def get_boolean(self, key):
  106. # Convert a value to a boolean using "common sense" rules.
  107. # Unset, empty, "0" and "false" (i-case) yield False.
  108. # All other values yield True.
  109. value = self.get(key)
  110. if not value:
  111. return False
  112. if value.lower() in ['0', 'false']:
  113. return False
  114. return True