config.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. # -*- coding: utf-8 -*-
  2. """
  3. flask.config
  4. ~~~~~~~~~~~~
  5. Implements the configuration related objects.
  6. :copyright: (c) 2015 by Armin Ronacher.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. import os
  10. import types
  11. import errno
  12. from werkzeug.utils import import_string
  13. from ._compat import string_types, iteritems
  14. from . import json
  15. class ConfigAttribute(object):
  16. """Makes an attribute forward to the config"""
  17. def __init__(self, name, get_converter=None):
  18. self.__name__ = name
  19. self.get_converter = get_converter
  20. def __get__(self, obj, type=None):
  21. if obj is None:
  22. return self
  23. rv = obj.config[self.__name__]
  24. if self.get_converter is not None:
  25. rv = self.get_converter(rv)
  26. return rv
  27. def __set__(self, obj, value):
  28. obj.config[self.__name__] = value
  29. class Config(dict):
  30. """Works exactly like a dict but provides ways to fill it from files
  31. or special dictionaries. There are two common patterns to populate the
  32. config.
  33. Either you can fill the config from a config file::
  34. app.config.from_pyfile('yourconfig.cfg')
  35. Or alternatively you can define the configuration options in the
  36. module that calls :meth:`from_object` or provide an import path to
  37. a module that should be loaded. It is also possible to tell it to
  38. use the same module and with that provide the configuration values
  39. just before the call::
  40. DEBUG = True
  41. SECRET_KEY = 'development key'
  42. app.config.from_object(__name__)
  43. In both cases (loading from any Python file or loading from modules),
  44. only uppercase keys are added to the config. This makes it possible to use
  45. lowercase values in the config file for temporary values that are not added
  46. to the config or to define the config keys in the same file that implements
  47. the application.
  48. Probably the most interesting way to load configurations is from an
  49. environment variable pointing to a file::
  50. app.config.from_envvar('YOURAPPLICATION_SETTINGS')
  51. In this case before launching the application you have to set this
  52. environment variable to the file you want to use. On Linux and OS X
  53. use the export statement::
  54. export YOURAPPLICATION_SETTINGS='/path/to/config/file'
  55. On windows use `set` instead.
  56. :param root_path: path to which files are read relative from. When the
  57. config object is created by the application, this is
  58. the application's :attr:`~flask.Flask.root_path`.
  59. :param defaults: an optional dictionary of default values
  60. """
  61. def __init__(self, root_path, defaults=None):
  62. dict.__init__(self, defaults or {})
  63. self.root_path = root_path
  64. def from_envvar(self, variable_name, silent=False):
  65. """Loads a configuration from an environment variable pointing to
  66. a configuration file. This is basically just a shortcut with nicer
  67. error messages for this line of code::
  68. app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
  69. :param variable_name: name of the environment variable
  70. :param silent: set to ``True`` if you want silent failure for missing
  71. files.
  72. :return: bool. ``True`` if able to load config, ``False`` otherwise.
  73. """
  74. rv = os.environ.get(variable_name)
  75. if not rv:
  76. if silent:
  77. return False
  78. raise RuntimeError('The environment variable %r is not set '
  79. 'and as such configuration could not be '
  80. 'loaded. Set this variable and make it '
  81. 'point to a configuration file' %
  82. variable_name)
  83. return self.from_pyfile(rv, silent=silent)
  84. def from_pyfile(self, filename, silent=False):
  85. """Updates the values in the config from a Python file. This function
  86. behaves as if the file was imported as module with the
  87. :meth:`from_object` function.
  88. :param filename: the filename of the config. This can either be an
  89. absolute filename or a filename relative to the
  90. root path.
  91. :param silent: set to ``True`` if you want silent failure for missing
  92. files.
  93. .. versionadded:: 0.7
  94. `silent` parameter.
  95. """
  96. filename = os.path.join(self.root_path, filename)
  97. d = types.ModuleType('config')
  98. d.__file__ = filename
  99. try:
  100. with open(filename) as config_file:
  101. exec(compile(config_file.read(), filename, 'exec'), d.__dict__)
  102. except IOError as e:
  103. if silent and e.errno in (errno.ENOENT, errno.EISDIR):
  104. return False
  105. e.strerror = 'Unable to load configuration file (%s)' % e.strerror
  106. raise
  107. self.from_object(d)
  108. return True
  109. def from_object(self, obj):
  110. """Updates the values from the given object. An object can be of one
  111. of the following two types:
  112. - a string: in this case the object with that name will be imported
  113. - an actual object reference: that object is used directly
  114. Objects are usually either modules or classes.
  115. Just the uppercase variables in that object are stored in the config.
  116. Example usage::
  117. app.config.from_object('yourapplication.default_config')
  118. from yourapplication import default_config
  119. app.config.from_object(default_config)
  120. You should not use this function to load the actual configuration but
  121. rather configuration defaults. The actual config should be loaded
  122. with :meth:`from_pyfile` and ideally from a location not within the
  123. package because the package might be installed system wide.
  124. :param obj: an import name or object
  125. """
  126. if isinstance(obj, string_types):
  127. obj = import_string(obj)
  128. for key in dir(obj):
  129. if key.isupper():
  130. self[key] = getattr(obj, key)
  131. def from_json(self, filename, silent=False):
  132. """Updates the values in the config from a JSON file. This function
  133. behaves as if the JSON object was a dictionary and passed to the
  134. :meth:`from_mapping` function.
  135. :param filename: the filename of the JSON file. This can either be an
  136. absolute filename or a filename relative to the
  137. root path.
  138. :param silent: set to ``True`` if you want silent failure for missing
  139. files.
  140. .. versionadded:: 0.11
  141. """
  142. filename = os.path.join(self.root_path, filename)
  143. try:
  144. with open(filename) as json_file:
  145. obj = json.loads(json_file.read())
  146. except IOError as e:
  147. if silent and e.errno in (errno.ENOENT, errno.EISDIR):
  148. return False
  149. e.strerror = 'Unable to load configuration file (%s)' % e.strerror
  150. raise
  151. return self.from_mapping(obj)
  152. def from_mapping(self, *mapping, **kwargs):
  153. """Updates the config like :meth:`update` ignoring items with non-upper
  154. keys.
  155. .. versionadded:: 0.11
  156. """
  157. mappings = []
  158. if len(mapping) == 1:
  159. if hasattr(mapping[0], 'items'):
  160. mappings.append(mapping[0].items())
  161. else:
  162. mappings.append(mapping[0])
  163. elif len(mapping) > 1:
  164. raise TypeError(
  165. 'expected at most 1 positional argument, got %d' % len(mapping)
  166. )
  167. mappings.append(kwargs.items())
  168. for mapping in mappings:
  169. for (key, value) in mapping:
  170. if key.isupper():
  171. self[key] = value
  172. return True
  173. def get_namespace(self, namespace, lowercase=True, trim_namespace=True):
  174. """Returns a dictionary containing a subset of configuration options
  175. that match the specified namespace/prefix. Example usage::
  176. app.config['IMAGE_STORE_TYPE'] = 'fs'
  177. app.config['IMAGE_STORE_PATH'] = '/var/app/images'
  178. app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'
  179. image_store_config = app.config.get_namespace('IMAGE_STORE_')
  180. The resulting dictionary `image_store_config` would look like::
  181. {
  182. 'type': 'fs',
  183. 'path': '/var/app/images',
  184. 'base_url': 'http://img.website.com'
  185. }
  186. This is often useful when configuration options map directly to
  187. keyword arguments in functions or class constructors.
  188. :param namespace: a configuration namespace
  189. :param lowercase: a flag indicating if the keys of the resulting
  190. dictionary should be lowercase
  191. :param trim_namespace: a flag indicating if the keys of the resulting
  192. dictionary should not include the namespace
  193. .. versionadded:: 0.11
  194. """
  195. rv = {}
  196. for k, v in iteritems(self):
  197. if not k.startswith(namespace):
  198. continue
  199. if trim_namespace:
  200. key = k[len(namespace):]
  201. else:
  202. key = k
  203. if lowercase:
  204. key = key.lower()
  205. rv[key] = v
  206. return rv
  207. def __repr__(self):
  208. return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self))