config.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. # -*- coding: utf-8 -*-
  2. """
  3. flask.config
  4. ~~~~~~~~~~~~
  5. Implements the configuration related objects.
  6. :copyright: © 2010 by the Pallets team.
  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, mode='rb') 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 (
  104. errno.ENOENT, errno.EISDIR, errno.ENOTDIR
  105. ):
  106. return False
  107. e.strerror = 'Unable to load configuration file (%s)' % e.strerror
  108. raise
  109. self.from_object(d)
  110. return True
  111. def from_object(self, obj):
  112. """Updates the values from the given object. An object can be of one
  113. of the following two types:
  114. - a string: in this case the object with that name will be imported
  115. - an actual object reference: that object is used directly
  116. Objects are usually either modules or classes. :meth:`from_object`
  117. loads only the uppercase attributes of the module/class. A ``dict``
  118. object will not work with :meth:`from_object` because the keys of a
  119. ``dict`` are not attributes of the ``dict`` class.
  120. Example of module-based configuration::
  121. app.config.from_object('yourapplication.default_config')
  122. from yourapplication import default_config
  123. app.config.from_object(default_config)
  124. You should not use this function to load the actual configuration but
  125. rather configuration defaults. The actual config should be loaded
  126. with :meth:`from_pyfile` and ideally from a location not within the
  127. package because the package might be installed system wide.
  128. See :ref:`config-dev-prod` for an example of class-based configuration
  129. using :meth:`from_object`.
  130. :param obj: an import name or object
  131. """
  132. if isinstance(obj, string_types):
  133. obj = import_string(obj)
  134. for key in dir(obj):
  135. if key.isupper():
  136. self[key] = getattr(obj, key)
  137. def from_json(self, filename, silent=False):
  138. """Updates the values in the config from a JSON file. This function
  139. behaves as if the JSON object was a dictionary and passed to the
  140. :meth:`from_mapping` function.
  141. :param filename: the filename of the JSON file. This can either be an
  142. absolute filename or a filename relative to the
  143. root path.
  144. :param silent: set to ``True`` if you want silent failure for missing
  145. files.
  146. .. versionadded:: 0.11
  147. """
  148. filename = os.path.join(self.root_path, filename)
  149. try:
  150. with open(filename) as json_file:
  151. obj = json.loads(json_file.read())
  152. except IOError as e:
  153. if silent and e.errno in (errno.ENOENT, errno.EISDIR):
  154. return False
  155. e.strerror = 'Unable to load configuration file (%s)' % e.strerror
  156. raise
  157. return self.from_mapping(obj)
  158. def from_mapping(self, *mapping, **kwargs):
  159. """Updates the config like :meth:`update` ignoring items with non-upper
  160. keys.
  161. .. versionadded:: 0.11
  162. """
  163. mappings = []
  164. if len(mapping) == 1:
  165. if hasattr(mapping[0], 'items'):
  166. mappings.append(mapping[0].items())
  167. else:
  168. mappings.append(mapping[0])
  169. elif len(mapping) > 1:
  170. raise TypeError(
  171. 'expected at most 1 positional argument, got %d' % len(mapping)
  172. )
  173. mappings.append(kwargs.items())
  174. for mapping in mappings:
  175. for (key, value) in mapping:
  176. if key.isupper():
  177. self[key] = value
  178. return True
  179. def get_namespace(self, namespace, lowercase=True, trim_namespace=True):
  180. """Returns a dictionary containing a subset of configuration options
  181. that match the specified namespace/prefix. Example usage::
  182. app.config['IMAGE_STORE_TYPE'] = 'fs'
  183. app.config['IMAGE_STORE_PATH'] = '/var/app/images'
  184. app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'
  185. image_store_config = app.config.get_namespace('IMAGE_STORE_')
  186. The resulting dictionary `image_store_config` would look like::
  187. {
  188. 'type': 'fs',
  189. 'path': '/var/app/images',
  190. 'base_url': 'http://img.website.com'
  191. }
  192. This is often useful when configuration options map directly to
  193. keyword arguments in functions or class constructors.
  194. :param namespace: a configuration namespace
  195. :param lowercase: a flag indicating if the keys of the resulting
  196. dictionary should be lowercase
  197. :param trim_namespace: a flag indicating if the keys of the resulting
  198. dictionary should not include the namespace
  199. .. versionadded:: 0.11
  200. """
  201. rv = {}
  202. for k, v in iteritems(self):
  203. if not k.startswith(namespace):
  204. continue
  205. if trim_namespace:
  206. key = k[len(namespace):]
  207. else:
  208. key = k
  209. if lowercase:
  210. key = key.lower()
  211. rv[key] = v
  212. return rv
  213. def __repr__(self):
  214. return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self))