config.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. import errno
  2. import os
  3. import types
  4. import typing as t
  5. from werkzeug.utils import import_string
  6. class ConfigAttribute:
  7. """Makes an attribute forward to the config"""
  8. def __init__(self, name: str, get_converter: t.Optional[t.Callable] = None) -> None:
  9. self.__name__ = name
  10. self.get_converter = get_converter
  11. def __get__(self, obj: t.Any, owner: t.Any = None) -> t.Any:
  12. if obj is None:
  13. return self
  14. rv = obj.config[self.__name__]
  15. if self.get_converter is not None:
  16. rv = self.get_converter(rv)
  17. return rv
  18. def __set__(self, obj: t.Any, value: t.Any) -> None:
  19. obj.config[self.__name__] = value
  20. class Config(dict):
  21. """Works exactly like a dict but provides ways to fill it from files
  22. or special dictionaries. There are two common patterns to populate the
  23. config.
  24. Either you can fill the config from a config file::
  25. app.config.from_pyfile('yourconfig.cfg')
  26. Or alternatively you can define the configuration options in the
  27. module that calls :meth:`from_object` or provide an import path to
  28. a module that should be loaded. It is also possible to tell it to
  29. use the same module and with that provide the configuration values
  30. just before the call::
  31. DEBUG = True
  32. SECRET_KEY = 'development key'
  33. app.config.from_object(__name__)
  34. In both cases (loading from any Python file or loading from modules),
  35. only uppercase keys are added to the config. This makes it possible to use
  36. lowercase values in the config file for temporary values that are not added
  37. to the config or to define the config keys in the same file that implements
  38. the application.
  39. Probably the most interesting way to load configurations is from an
  40. environment variable pointing to a file::
  41. app.config.from_envvar('YOURAPPLICATION_SETTINGS')
  42. In this case before launching the application you have to set this
  43. environment variable to the file you want to use. On Linux and OS X
  44. use the export statement::
  45. export YOURAPPLICATION_SETTINGS='/path/to/config/file'
  46. On windows use `set` instead.
  47. :param root_path: path to which files are read relative from. When the
  48. config object is created by the application, this is
  49. the application's :attr:`~flask.Flask.root_path`.
  50. :param defaults: an optional dictionary of default values
  51. """
  52. def __init__(self, root_path: str, defaults: t.Optional[dict] = None) -> None:
  53. dict.__init__(self, defaults or {})
  54. self.root_path = root_path
  55. def from_envvar(self, variable_name: str, silent: bool = False) -> bool:
  56. """Loads a configuration from an environment variable pointing to
  57. a configuration file. This is basically just a shortcut with nicer
  58. error messages for this line of code::
  59. app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
  60. :param variable_name: name of the environment variable
  61. :param silent: set to ``True`` if you want silent failure for missing
  62. files.
  63. :return: ``True`` if the file was loaded successfully.
  64. """
  65. rv = os.environ.get(variable_name)
  66. if not rv:
  67. if silent:
  68. return False
  69. raise RuntimeError(
  70. f"The environment variable {variable_name!r} is not set"
  71. " and as such configuration could not be loaded. Set"
  72. " this variable and make it point to a configuration"
  73. " file"
  74. )
  75. return self.from_pyfile(rv, silent=silent)
  76. def from_pyfile(self, filename: str, silent: bool = False) -> bool:
  77. """Updates the values in the config from a Python file. This function
  78. behaves as if the file was imported as module with the
  79. :meth:`from_object` function.
  80. :param filename: the filename of the config. This can either be an
  81. absolute filename or a filename relative to the
  82. root path.
  83. :param silent: set to ``True`` if you want silent failure for missing
  84. files.
  85. :return: ``True`` if the file was loaded successfully.
  86. .. versionadded:: 0.7
  87. `silent` parameter.
  88. """
  89. filename = os.path.join(self.root_path, filename)
  90. d = types.ModuleType("config")
  91. d.__file__ = filename
  92. try:
  93. with open(filename, mode="rb") as config_file:
  94. exec(compile(config_file.read(), filename, "exec"), d.__dict__)
  95. except OSError as e:
  96. if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):
  97. return False
  98. e.strerror = f"Unable to load configuration file ({e.strerror})"
  99. raise
  100. self.from_object(d)
  101. return True
  102. def from_object(self, obj: t.Union[object, str]) -> None:
  103. """Updates the values from the given object. An object can be of one
  104. of the following two types:
  105. - a string: in this case the object with that name will be imported
  106. - an actual object reference: that object is used directly
  107. Objects are usually either modules or classes. :meth:`from_object`
  108. loads only the uppercase attributes of the module/class. A ``dict``
  109. object will not work with :meth:`from_object` because the keys of a
  110. ``dict`` are not attributes of the ``dict`` class.
  111. Example of module-based configuration::
  112. app.config.from_object('yourapplication.default_config')
  113. from yourapplication import default_config
  114. app.config.from_object(default_config)
  115. Nothing is done to the object before loading. If the object is a
  116. class and has ``@property`` attributes, it needs to be
  117. instantiated before being passed to this method.
  118. You should not use this function to load the actual configuration but
  119. rather configuration defaults. The actual config should be loaded
  120. with :meth:`from_pyfile` and ideally from a location not within the
  121. package because the package might be installed system wide.
  122. See :ref:`config-dev-prod` for an example of class-based configuration
  123. using :meth:`from_object`.
  124. :param obj: an import name or object
  125. """
  126. if isinstance(obj, str):
  127. obj = import_string(obj)
  128. for key in dir(obj):
  129. if key.isupper():
  130. self[key] = getattr(obj, key)
  131. def from_file(
  132. self,
  133. filename: str,
  134. load: t.Callable[[t.IO[t.Any]], t.Mapping],
  135. silent: bool = False,
  136. ) -> bool:
  137. """Update the values in the config from a file that is loaded
  138. using the ``load`` parameter. The loaded data is passed to the
  139. :meth:`from_mapping` method.
  140. .. code-block:: python
  141. import toml
  142. app.config.from_file("config.toml", load=toml.load)
  143. :param filename: The path to the data file. This can be an
  144. absolute path or relative to the config root path.
  145. :param load: A callable that takes a file handle and returns a
  146. mapping of loaded data from the file.
  147. :type load: ``Callable[[Reader], Mapping]`` where ``Reader``
  148. implements a ``read`` method.
  149. :param silent: Ignore the file if it doesn't exist.
  150. :return: ``True`` if the file was loaded successfully.
  151. .. versionadded:: 2.0
  152. """
  153. filename = os.path.join(self.root_path, filename)
  154. try:
  155. with open(filename) as f:
  156. obj = load(f)
  157. except OSError as e:
  158. if silent and e.errno in (errno.ENOENT, errno.EISDIR):
  159. return False
  160. e.strerror = f"Unable to load configuration file ({e.strerror})"
  161. raise
  162. return self.from_mapping(obj)
  163. def from_json(self, filename: str, silent: bool = False) -> bool:
  164. """Update the values in the config from a JSON file. The loaded
  165. data is passed to the :meth:`from_mapping` method.
  166. :param filename: The path to the JSON file. This can be an
  167. absolute path or relative to the config root path.
  168. :param silent: Ignore the file if it doesn't exist.
  169. :return: ``True`` if the file was loaded successfully.
  170. .. deprecated:: 2.0.0
  171. Will be removed in Flask 2.1. Use :meth:`from_file` instead.
  172. This was removed early in 2.0.0, was added back in 2.0.1.
  173. .. versionadded:: 0.11
  174. """
  175. import warnings
  176. from . import json
  177. warnings.warn(
  178. "'from_json' is deprecated and will be removed in Flask"
  179. " 2.1. Use 'from_file(path, json.load)' instead.",
  180. DeprecationWarning,
  181. stacklevel=2,
  182. )
  183. return self.from_file(filename, json.load, silent=silent)
  184. def from_mapping(
  185. self, mapping: t.Optional[t.Mapping[str, t.Any]] = None, **kwargs: t.Any
  186. ) -> bool:
  187. """Updates the config like :meth:`update` ignoring items with non-upper
  188. keys.
  189. :return: Always returns ``True``.
  190. .. versionadded:: 0.11
  191. """
  192. mappings: t.Dict[str, t.Any] = {}
  193. if mapping is not None:
  194. mappings.update(mapping)
  195. mappings.update(kwargs)
  196. for key, value in mappings.items():
  197. if key.isupper():
  198. self[key] = value
  199. return True
  200. def get_namespace(
  201. self, namespace: str, lowercase: bool = True, trim_namespace: bool = True
  202. ) -> t.Dict[str, t.Any]:
  203. """Returns a dictionary containing a subset of configuration options
  204. that match the specified namespace/prefix. Example usage::
  205. app.config['IMAGE_STORE_TYPE'] = 'fs'
  206. app.config['IMAGE_STORE_PATH'] = '/var/app/images'
  207. app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'
  208. image_store_config = app.config.get_namespace('IMAGE_STORE_')
  209. The resulting dictionary `image_store_config` would look like::
  210. {
  211. 'type': 'fs',
  212. 'path': '/var/app/images',
  213. 'base_url': 'http://img.website.com'
  214. }
  215. This is often useful when configuration options map directly to
  216. keyword arguments in functions or class constructors.
  217. :param namespace: a configuration namespace
  218. :param lowercase: a flag indicating if the keys of the resulting
  219. dictionary should be lowercase
  220. :param trim_namespace: a flag indicating if the keys of the resulting
  221. dictionary should not include the namespace
  222. .. versionadded:: 0.11
  223. """
  224. rv = {}
  225. for k, v in self.items():
  226. if not k.startswith(namespace):
  227. continue
  228. if trim_namespace:
  229. key = k[len(namespace) :]
  230. else:
  231. key = k
  232. if lowercase:
  233. key = key.lower()
  234. rv[key] = v
  235. return rv
  236. def __repr__(self) -> str:
  237. return f"<{type(self).__name__} {dict.__repr__(self)}>"