]>
jfr.im git - dlqueue.git/blob - venv/lib/python3.11/site-packages/flask/config.py
1 from __future__
import annotations
9 from werkzeug
.utils
import import_string
12 class ConfigAttribute
:
13 """Makes an attribute forward to the config"""
15 def __init__(self
, name
: str, get_converter
: t
.Callable |
None = None) -> None:
17 self
.get_converter
= get_converter
19 def __get__(self
, obj
: t
.Any
, owner
: t
.Any
= None) -> t
.Any
:
22 rv
= obj
.config
[self
.__name
__]
23 if self
.get_converter
is not None:
24 rv
= self
.get_converter(rv
)
27 def __set__(self
, obj
: t
.Any
, value
: t
.Any
) -> None:
28 obj
.config
[self
.__name
__] = value
32 """Works exactly like a dict but provides ways to fill it from files
33 or special dictionaries. There are two common patterns to populate the
36 Either you can fill the config from a config file::
38 app.config.from_pyfile('yourconfig.cfg')
40 Or alternatively you can define the configuration options in the
41 module that calls :meth:`from_object` or provide an import path to
42 a module that should be loaded. It is also possible to tell it to
43 use the same module and with that provide the configuration values
44 just before the call::
47 SECRET_KEY = 'development key'
48 app.config.from_object(__name__)
50 In both cases (loading from any Python file or loading from modules),
51 only uppercase keys are added to the config. This makes it possible to use
52 lowercase values in the config file for temporary values that are not added
53 to the config or to define the config keys in the same file that implements
56 Probably the most interesting way to load configurations is from an
57 environment variable pointing to a file::
59 app.config.from_envvar('YOURAPPLICATION_SETTINGS')
61 In this case before launching the application you have to set this
62 environment variable to the file you want to use. On Linux and OS X
63 use the export statement::
65 export YOURAPPLICATION_SETTINGS='/path/to/config/file'
67 On windows use `set` instead.
69 :param root_path: path to which files are read relative from. When the
70 config object is created by the application, this is
71 the application's :attr:`~flask.Flask.root_path`.
72 :param defaults: an optional dictionary of default values
76 self
, root_path
: str | os
.PathLike
, defaults
: dict |
None = None
78 super().__init
__(defaults
or {})
79 self
.root_path
= root_path
81 def from_envvar(self
, variable_name
: str, silent
: bool = False) -> bool:
82 """Loads a configuration from an environment variable pointing to
83 a configuration file. This is basically just a shortcut with nicer
84 error messages for this line of code::
86 app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
88 :param variable_name: name of the environment variable
89 :param silent: set to ``True`` if you want silent failure for missing
91 :return: ``True`` if the file was loaded successfully.
93 rv
= os
.environ
.get(variable_name
)
98 f
"The environment variable {variable_name!r} is not set"
99 " and as such configuration could not be loaded. Set"
100 " this variable and make it point to a configuration"
103 return self
.from_pyfile(rv
, silent
=silent
)
105 def from_prefixed_env(
106 self
, prefix
: str = "FLASK", *, loads
: t
.Callable
[[str], t
.Any
] = json
.loads
108 """Load any environment variables that start with ``FLASK_``,
109 dropping the prefix from the env key for the config key. Values
110 are passed through a loading function to attempt to convert them
111 to more specific types than strings.
113 Keys are loaded in :func:`sorted` order.
115 The default loading function attempts to parse values as any
116 valid JSON type, including dicts and lists.
118 Specific items in nested dicts can be set by separating the
119 keys with double underscores (``__``). If an intermediate key
120 doesn't exist, it will be initialized to an empty dict.
122 :param prefix: Load env vars that start with this prefix,
123 separated with an underscore (``_``).
124 :param loads: Pass each string value to this function and use
125 the returned value as the config value. If any error is
126 raised it is ignored and the value remains a string. The
127 default is :func:`json.loads`.
129 .. versionadded:: 2.1
131 prefix
= f
"{prefix}_"
132 len_prefix
= len(prefix
)
134 for key
in sorted(os
.environ
):
135 if not key
.startswith(prefix
):
138 value
= os
.environ
[key
]
143 # Keep the value as a string if loading failed.
146 # Change to key.removeprefix(prefix) on Python >= 3.9.
147 key
= key
[len_prefix
:]
150 # A non-nested key, set directly.
154 # Traverse nested dictionaries with keys separated by "__".
156 *parts
, tail
= key
.split("__")
159 # If an intermediate dict does not exist, create it.
160 if part
not in current
:
163 current
= current
[part
]
165 current
[tail
] = value
169 def from_pyfile(self
, filename
: str | os
.PathLike
, silent
: bool = False) -> bool:
170 """Updates the values in the config from a Python file. This function
171 behaves as if the file was imported as module with the
172 :meth:`from_object` function.
174 :param filename: the filename of the config. This can either be an
175 absolute filename or a filename relative to the
177 :param silent: set to ``True`` if you want silent failure for missing
179 :return: ``True`` if the file was loaded successfully.
181 .. versionadded:: 0.7
184 filename
= os
.path
.join(self
.root_path
, filename
)
185 d
= types
.ModuleType("config")
186 d
.__file
__ = filename
188 with open(filename
, mode
="rb") as config_file
:
189 exec(compile(config_file
.read(), filename
, "exec"), d
.__dict
__)
191 if silent
and e
.errno
in (errno
.ENOENT
, errno
.EISDIR
, errno
.ENOTDIR
):
193 e
.strerror
= f
"Unable to load configuration file ({e.strerror})"
198 def from_object(self
, obj
: object |
str) -> None:
199 """Updates the values from the given object. An object can be of one
200 of the following two types:
202 - a string: in this case the object with that name will be imported
203 - an actual object reference: that object is used directly
205 Objects are usually either modules or classes. :meth:`from_object`
206 loads only the uppercase attributes of the module/class. A ``dict``
207 object will not work with :meth:`from_object` because the keys of a
208 ``dict`` are not attributes of the ``dict`` class.
210 Example of module-based configuration::
212 app.config.from_object('yourapplication.default_config')
213 from yourapplication import default_config
214 app.config.from_object(default_config)
216 Nothing is done to the object before loading. If the object is a
217 class and has ``@property`` attributes, it needs to be
218 instantiated before being passed to this method.
220 You should not use this function to load the actual configuration but
221 rather configuration defaults. The actual config should be loaded
222 with :meth:`from_pyfile` and ideally from a location not within the
223 package because the package might be installed system wide.
225 See :ref:`config-dev-prod` for an example of class-based configuration
226 using :meth:`from_object`.
228 :param obj: an import name or object
230 if isinstance(obj
, str):
231 obj
= import_string(obj
)
234 self
[key
] = getattr(obj
, key
)
238 filename
: str | os
.PathLike
,
239 load
: t
.Callable
[[t
.IO
[t
.Any
]], t
.Mapping
],
240 silent
: bool = False,
243 """Update the values in the config from a file that is loaded
244 using the ``load`` parameter. The loaded data is passed to the
245 :meth:`from_mapping` method.
247 .. code-block:: python
250 app.config.from_file("config.json", load=json.load)
253 app.config.from_file("config.toml", load=tomllib.load, text=False)
255 :param filename: The path to the data file. This can be an
256 absolute path or relative to the config root path.
257 :param load: A callable that takes a file handle and returns a
258 mapping of loaded data from the file.
259 :type load: ``Callable[[Reader], Mapping]`` where ``Reader``
260 implements a ``read`` method.
261 :param silent: Ignore the file if it doesn't exist.
262 :param text: Open the file in text or binary mode.
263 :return: ``True`` if the file was loaded successfully.
265 .. versionchanged:: 2.3
266 The ``text`` parameter was added.
268 .. versionadded:: 2.0
270 filename
= os
.path
.join(self
.root_path
, filename
)
273 with open(filename
, "r" if text
else "rb") as f
:
276 if silent
and e
.errno
in (errno
.ENOENT
, errno
.EISDIR
):
279 e
.strerror
= f
"Unable to load configuration file ({e.strerror})"
282 return self
.from_mapping(obj
)
285 self
, mapping
: t
.Mapping
[str, t
.Any
] |
None = None, **kwargs
: t
.Any
287 """Updates the config like :meth:`update` ignoring items with
290 :return: Always returns ``True``.
292 .. versionadded:: 0.11
294 mappings
: dict[str, t
.Any
] = {}
295 if mapping
is not None:
296 mappings
.update(mapping
)
297 mappings
.update(kwargs
)
298 for key
, value
in mappings
.items():
304 self
, namespace
: str, lowercase
: bool = True, trim_namespace
: bool = True
305 ) -> dict[str, t
.Any
]:
306 """Returns a dictionary containing a subset of configuration options
307 that match the specified namespace/prefix. Example usage::
309 app.config['IMAGE_STORE_TYPE'] = 'fs'
310 app.config['IMAGE_STORE_PATH'] = '/var/app/images'
311 app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'
312 image_store_config = app.config.get_namespace('IMAGE_STORE_')
314 The resulting dictionary `image_store_config` would look like::
318 'path': '/var/app/images',
319 'base_url': 'http://img.website.com'
322 This is often useful when configuration options map directly to
323 keyword arguments in functions or class constructors.
325 :param namespace: a configuration namespace
326 :param lowercase: a flag indicating if the keys of the resulting
327 dictionary should be lowercase
328 :param trim_namespace: a flag indicating if the keys of the resulting
329 dictionary should not include the namespace
331 .. versionadded:: 0.11
334 for k
, v
in self
.items():
335 if not k
.startswith(namespace
):
338 key
= k
[len(namespace
) :]
346 def __repr__(self
) -> str:
347 return f
"<{type(self).__name__} {dict.__repr__(self)}>"