environment.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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. self.silent = False
  50. @classmethod
  51. def from_env_file(cls, base_dir):
  52. def _initialize():
  53. result = cls()
  54. if base_dir is None:
  55. return result
  56. env_file_path = os.path.join(base_dir, '.env')
  57. try:
  58. return cls(env_vars_from_file(env_file_path))
  59. except EnvFileNotFound:
  60. pass
  61. return result
  62. instance = _initialize()
  63. instance.update(os.environ)
  64. return instance
  65. @classmethod
  66. def from_command_line(cls, parsed_env_opts):
  67. result = cls()
  68. for k, v in parsed_env_opts.items():
  69. # Values from the command line take priority, unless they're unset
  70. # in which case they take the value from the system's environment
  71. if v is None and k in os.environ:
  72. result[k] = os.environ[k]
  73. else:
  74. result[k] = v
  75. return result
  76. def __getitem__(self, key):
  77. try:
  78. return super(Environment, self).__getitem__(key)
  79. except KeyError:
  80. if IS_WINDOWS_PLATFORM:
  81. try:
  82. return super(Environment, self).__getitem__(key.upper())
  83. except KeyError:
  84. pass
  85. if not self.silent and key not in self.missing_keys:
  86. log.warn(
  87. "The {} variable is not set. Defaulting to a blank string."
  88. .format(key)
  89. )
  90. self.missing_keys.append(key)
  91. return ""
  92. def __contains__(self, key):
  93. result = super(Environment, self).__contains__(key)
  94. if IS_WINDOWS_PLATFORM:
  95. return (
  96. result or super(Environment, self).__contains__(key.upper())
  97. )
  98. return result
  99. def get(self, key, *args, **kwargs):
  100. if IS_WINDOWS_PLATFORM:
  101. return super(Environment, self).get(
  102. key,
  103. super(Environment, self).get(key.upper(), *args, **kwargs)
  104. )
  105. return super(Environment, self).get(key, *args, **kwargs)
  106. def get_boolean(self, key):
  107. # Convert a value to a boolean using "common sense" rules.
  108. # Unset, empty, "0" and "false" (i-case) yield False.
  109. # All other values yield True.
  110. value = self.get(key)
  111. if not value:
  112. return False
  113. if value.lower() in ['0', 'false']:
  114. return False
  115. return True