environment.py 3.9 KB

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