add text parameter to config.from_file

This commit is contained in:
AntoineMath 2023-02-22 14:40:49 +01:00 committed by David Lord
parent 4c288bc97e
commit b10b6d4af1
No known key found for this signature in database
GPG key ID: 7A1C87E3F5BC42A8
4 changed files with 23 additions and 5 deletions

View file

@ -234,6 +234,7 @@ class Config(dict):
filename: str,
load: t.Callable[[t.IO[t.Any]], t.Mapping],
silent: bool = False,
text: bool = True,
) -> bool:
"""Update the values in the config from a file that is loaded
using the ``load`` parameter. The loaded data is passed to the
@ -244,8 +245,8 @@ class Config(dict):
import json
app.config.from_file("config.json", load=json.load)
import toml
app.config.from_file("config.toml", load=toml.load)
import tomllib
app.config.from_file("config.toml", load=tomllib.load, text=False)
:param filename: The path to the data file. This can be an
absolute path or relative to the config root path.
@ -254,14 +255,18 @@ class Config(dict):
:type load: ``Callable[[Reader], Mapping]`` where ``Reader``
implements a ``read`` method.
:param silent: Ignore the file if it doesn't exist.
:param text: Open the file in text or binary mode.
:return: ``True`` if the file was loaded successfully.
.. versionchanged:: 2.3
The ``text`` parameter was added.
.. versionadded:: 2.0
"""
filename = os.path.join(self.root_path, filename)
try:
with open(filename) as f:
with open(filename, "r" if text else "rb") as f:
obj = load(f)
except OSError as e:
if silent and e.errno in (errno.ENOENT, errno.EISDIR):