1
0

config.py 9.8 KB

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