config_manager.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. import imp
  2. import os
  3. import errno
  4. import sys
  5. string_types = (str,)
  6. def get_config():
  7. if get_config.instance is None:
  8. get_config.instance = Config(os.getcwd())
  9. return get_config.instance
  10. get_config.instance = None
  11. ## Stolen from flask.config
  12. class Config(dict):
  13. """Works exactly like a dict but provides ways to fill it from files
  14. or special dictionaries. There are two common patterns to populate the
  15. config.
  16. Either you can fill the config from a config file::
  17. app.config.from_pyfile('yourconfig.cfg')
  18. Or alternatively you can define the configuration options in the
  19. module that calls :meth:`from_object` or provide an import path to
  20. a module that should be loaded. It is also possible to tell it to
  21. use the same module and with that provide the configuration values
  22. just before the call::
  23. DEBUG = True
  24. SECRET_KEY = 'development key'
  25. app.config.from_object(__name__)
  26. In both cases (loading from any Python file or loading from modules),
  27. only uppercase keys are added to the config. This makes it possible to use
  28. lowercase values in the config file for temporary values that are not added
  29. to the config or to define the config keys in the same file that implements
  30. the application.
  31. Probably the most interesting way to load configurations is from an
  32. environment variable pointing to a file::
  33. app.config.from_envvar('YOURAPPLICATION_SETTINGS')
  34. In this case before launching the application you have to set this
  35. environment variable to the file you want to use. On Linux and OS X
  36. use the export statement::
  37. export YOURAPPLICATION_SETTINGS='/path/to/config/file'
  38. On windows use `set` instead.
  39. :param root_path: path to which files are read relative from. When the
  40. config object is created by the application, this is
  41. the application's :attr:`~flask.Flask.root_path`.
  42. :param defaults: an optional dictionary of default values
  43. """
  44. def __init__(self, root_path, defaults=None):
  45. dict.__init__(self, defaults or {})
  46. self.root_path = root_path
  47. def from_envvar(self, variable_name, silent=False):
  48. """Loads a configuration from an environment variable pointing to
  49. a configuration file. This is basically just a shortcut with nicer
  50. error messages for this line of code::
  51. app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
  52. :param variable_name: name of the environment variable
  53. :param silent: set to `True` if you want silent failure for missing
  54. files.
  55. :return: bool. `True` if able to load config, `False` otherwise.
  56. """
  57. rv = os.environ.get(variable_name)
  58. if not rv:
  59. if silent:
  60. return False
  61. raise RuntimeError(
  62. "The environment variable %r is not set "
  63. "and as such configuration could not be "
  64. "loaded. Set this variable and make it "
  65. "point to a configuration file" % variable_name
  66. )
  67. return self.from_pyfile(rv, silent=silent)
  68. def from_pyfile(self, filename, silent=False):
  69. """Updates the values in the config from a Python file. This function
  70. behaves as if the file was imported as module with the
  71. :meth:`from_object` function.
  72. :param filename: the filename of the config. This can either be an
  73. absolute filename or a filename relative to the
  74. root path.
  75. :param silent: set to `True` if you want silent failure for missing
  76. files.
  77. .. versionadded:: 0.7
  78. `silent` parameter.
  79. """
  80. filename = os.path.join(self.root_path, filename)
  81. d = imp.new_module("config")
  82. d.__file__ = filename
  83. try:
  84. with open(filename) as config_file:
  85. exec(compile(config_file.read(), filename, "exec"), d.__dict__)
  86. except IOError as e:
  87. if silent and e.errno in (errno.ENOENT, errno.EISDIR):
  88. return False
  89. e.strerror = "Unable to load configuration file (%s)" % e.strerror
  90. raise
  91. self.from_object(d)
  92. return True
  93. def from_object(self, obj):
  94. """Updates the values from the given object. An object can be of one
  95. of the following two types:
  96. - a string: in this case the object with that name will be imported
  97. - an actual object reference: that object is used directly
  98. Objects are usually either modules or classes.
  99. Just the uppercase variables in that object are stored in the config.
  100. Example usage::
  101. app.config.from_object('yourapplication.default_config')
  102. from yourapplication import default_config
  103. app.config.from_object(default_config)
  104. You should not use this function to load the actual configuration but
  105. rather configuration defaults. The actual config should be loaded
  106. with :meth:`from_pyfile` and ideally from a location not within the
  107. package because the package might be installed system wide.
  108. :param obj: an import name or object
  109. """
  110. if isinstance(obj, string_types):
  111. obj = import_string(obj)
  112. for key in dir(obj):
  113. if key.isupper():
  114. self[key] = getattr(obj, key)
  115. def __repr__(self):
  116. return "<%s %s>" % (self.__class__.__name__, dict.__repr__(self))
  117. def import_string(import_name, silent=False):
  118. """Imports an object based on a string. This is useful if you want to
  119. use import paths as endpoints or something similar. An import path can
  120. be specified either in dotted notation (``xml.sax.saxutils.escape``)
  121. or with a colon as object delimiter (``xml.sax.saxutils:escape``).
  122. If `silent` is True the return value will be `None` if the import fails.
  123. :param import_name: the dotted name for the object to import.
  124. :param silent: if set to `True` import errors are ignored and
  125. `None` is returned instead.
  126. :return: imported object
  127. """
  128. # XXX: py3 review needed
  129. assert isinstance(import_name, string_types)
  130. # force the import name to automatically convert to strings
  131. import_name = str(import_name)
  132. try:
  133. if ":" in import_name:
  134. module, obj = import_name.split(":", 1)
  135. elif "." in import_name:
  136. module, obj = import_name.rsplit(".", 1)
  137. else:
  138. return __import__(import_name)
  139. # __import__ is not able to handle unicode strings in the fromlist
  140. # if the module is a package
  141. if sys.version_info[0] == 2 and isinstance(obj, unicode):
  142. obj = obj.encode("utf-8")
  143. try:
  144. return getattr(__import__(module, None, None, [obj]), obj)
  145. except (ImportError, AttributeError):
  146. # support importing modules not yet set up by the parent module
  147. # (or package for that matter)
  148. modname = module + "." + obj
  149. __import__(modname)
  150. return sys.modules[modname]
  151. except ImportError as e:
  152. if not silent:
  153. raise e