No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

292 líneas
11KB

  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: bool. ``True`` if able to load config, ``False`` otherwise.
  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. .. versionadded:: 0.7
  86. `silent` parameter.
  87. """
  88. filename = os.path.join(self.root_path, filename)
  89. d = types.ModuleType("config")
  90. d.__file__ = filename
  91. try:
  92. with open(filename, mode="rb") as config_file:
  93. exec(compile(config_file.read(), filename, "exec"), d.__dict__)
  94. except OSError as e:
  95. if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):
  96. return False
  97. e.strerror = f"Unable to load configuration file ({e.strerror})"
  98. raise
  99. self.from_object(d)
  100. return True
  101. def from_object(self, obj: t.Union[object, str]) -> None:
  102. """Updates the values from the given object. An object can be of one
  103. of the following two types:
  104. - a string: in this case the object with that name will be imported
  105. - an actual object reference: that object is used directly
  106. Objects are usually either modules or classes. :meth:`from_object`
  107. loads only the uppercase attributes of the module/class. A ``dict``
  108. object will not work with :meth:`from_object` because the keys of a
  109. ``dict`` are not attributes of the ``dict`` class.
  110. Example of module-based configuration::
  111. app.config.from_object('yourapplication.default_config')
  112. from yourapplication import default_config
  113. app.config.from_object(default_config)
  114. Nothing is done to the object before loading. If the object is a
  115. class and has ``@property`` attributes, it needs to be
  116. instantiated before being passed to this method.
  117. You should not use this function to load the actual configuration but
  118. rather configuration defaults. The actual config should be loaded
  119. with :meth:`from_pyfile` and ideally from a location not within the
  120. package because the package might be installed system wide.
  121. See :ref:`config-dev-prod` for an example of class-based configuration
  122. using :meth:`from_object`.
  123. :param obj: an import name or object
  124. """
  125. if isinstance(obj, str):
  126. obj = import_string(obj)
  127. for key in dir(obj):
  128. if key.isupper():
  129. self[key] = getattr(obj, key)
  130. def from_file(
  131. self,
  132. filename: str,
  133. load: t.Callable[[t.IO[t.Any]], t.Mapping],
  134. silent: bool = False,
  135. ) -> bool:
  136. """Update the values in the config from a file that is loaded
  137. using the ``load`` parameter. The loaded data is passed to the
  138. :meth:`from_mapping` method.
  139. .. code-block:: python
  140. import toml
  141. app.config.from_file("config.toml", load=toml.load)
  142. :param filename: The path to the data file. This can be an
  143. absolute path or relative to the config root path.
  144. :param load: A callable that takes a file handle and returns a
  145. mapping of loaded data from the file.
  146. :type load: ``Callable[[Reader], Mapping]`` where ``Reader``
  147. implements a ``read`` method.
  148. :param silent: Ignore the file if it doesn't exist.
  149. .. versionadded:: 2.0
  150. """
  151. filename = os.path.join(self.root_path, filename)
  152. try:
  153. with open(filename) as f:
  154. obj = load(f)
  155. except OSError as e:
  156. if silent and e.errno in (errno.ENOENT, errno.EISDIR):
  157. return False
  158. e.strerror = f"Unable to load configuration file ({e.strerror})"
  159. raise
  160. return self.from_mapping(obj)
  161. def from_json(self, filename: str, silent: bool = False) -> bool:
  162. """Update the values in the config from a JSON file. The loaded
  163. data is passed to the :meth:`from_mapping` method.
  164. :param filename: The path to the JSON file. This can be an
  165. absolute path or relative to the config root path.
  166. :param silent: Ignore the file if it doesn't exist.
  167. .. deprecated:: 2.0.0
  168. Will be removed in Flask 2.1. Use :meth:`from_file` instead.
  169. This was removed early in 2.0.0, was added back in 2.0.1.
  170. .. versionadded:: 0.11
  171. """
  172. import warnings
  173. from . import json
  174. warnings.warn(
  175. "'from_json' is deprecated and will be removed in Flask"
  176. " 2.1. Use 'from_file(path, json.load)' instead.",
  177. DeprecationWarning,
  178. stacklevel=2,
  179. )
  180. return self.from_file(filename, json.load, silent=silent)
  181. def from_mapping(
  182. self, mapping: t.Optional[t.Mapping[str, t.Any]] = None, **kwargs: t.Any
  183. ) -> bool:
  184. """Updates the config like :meth:`update` ignoring items with non-upper
  185. keys.
  186. .. versionadded:: 0.11
  187. """
  188. mappings: t.Dict[str, t.Any] = {}
  189. if mapping is not None:
  190. mappings.update(mapping)
  191. mappings.update(kwargs)
  192. for key, value in mappings.items():
  193. if key.isupper():
  194. self[key] = value
  195. return True
  196. def get_namespace(
  197. self, namespace: str, lowercase: bool = True, trim_namespace: bool = True
  198. ) -> t.Dict[str, t.Any]:
  199. """Returns a dictionary containing a subset of configuration options
  200. that match the specified namespace/prefix. Example usage::
  201. app.config['IMAGE_STORE_TYPE'] = 'fs'
  202. app.config['IMAGE_STORE_PATH'] = '/var/app/images'
  203. app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'
  204. image_store_config = app.config.get_namespace('IMAGE_STORE_')
  205. The resulting dictionary `image_store_config` would look like::
  206. {
  207. 'type': 'fs',
  208. 'path': '/var/app/images',
  209. 'base_url': 'http://img.website.com'
  210. }
  211. This is often useful when configuration options map directly to
  212. keyword arguments in functions or class constructors.
  213. :param namespace: a configuration namespace
  214. :param lowercase: a flag indicating if the keys of the resulting
  215. dictionary should be lowercase
  216. :param trim_namespace: a flag indicating if the keys of the resulting
  217. dictionary should not include the namespace
  218. .. versionadded:: 0.11
  219. """
  220. rv = {}
  221. for k, v in self.items():
  222. if not k.startswith(namespace):
  223. continue
  224. if trim_namespace:
  225. key = k[len(namespace) :]
  226. else:
  227. key = k
  228. if lowercase:
  229. key = key.lower()
  230. rv[key] = v
  231. return rv
  232. def __repr__(self) -> str:
  233. return f"<{type(self).__name__} {dict.__repr__(self)}>"