Support loading configuration from text files
Before adoption: this commit came in with the history the project adopted, so no landing records it.
TOML is a very popular format now, and is taking hold in the Python ecosystem via pyproject.toml (among others). This allows toml config files via, app.config.from_file("config.toml", toml.loads) it also allows for any other file format whereby there is a loader that takes a string and returns a mapping.
authored by pgjones · committed by David Lord · parent 7df10cd · Browse files · 3 files·+56 added−16 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+56 added−16 removed
- tests:+7 added−6 removed
- other:+49 added−10 removed
Provenance
- Commit
829aa65- Tree
41862cb- Author
pgjones <philip.graham.jones@googlemail.com>- Committer
David Lord <davidism@gmail.com>- Parent
7df10cd
3 files changed+56 added−16 removed
modified:docs/config.rst+16 added-2 removed
391 unmodified lines392 393 Added :data:`MAX_COOKIE_SIZE` to control a warning from Werkzeug.394 395 396-Configuring from Files397-----------------------396+Configuring from Python Files397+-----------------------------398 399 Configuration becomes more useful if you can store it in a separate file,400 ideally located outside the actual application package. This makes401 packaging and distributing your application possible via various package37 unmodified lines439 methods on the config object as well to load from individual files. For a440 complete reference, read the :class:`~flask.Config` object's441 documentation.442 443+Configuring from files444+----------------------445 446+It is also possible to load configure from a flat file in a format of447+your choice, for example to load from a TOML (or JSON) formatted448+file::449+450+ import json451+ import toml452+453+ app.config.from_file("config.toml", load=toml.load)454+ # Alternatively, if you prefer JSON455+ app.config.from_file("config.json", load=json.load)456+457+458 Configuring from Environment Variables459 --------------------------------------460 461 In addition to pointing to configuration files using environment variables, you250 unmodified linesmodified:src/flask/config.py+33 added-8 removed
9 unmodified lines10 """11 import errno12 import os13 import types14+import warnings15 16 from werkzeug.utils import import_string17 18 from . import json157 unmodified lines176 for key in dir(obj):177 if key.isupper():178 self[key] = getattr(obj, key)179 179- def from_json(self, filename, silent=False):180- """Updates the values in the config from a JSON file. This function181- behaves as if the JSON object was a dictionary and passed to the182- :meth:`from_mapping` function.180+ def from_file(self, filename, load, silent=False):181+ """Update the values in the config from a file that is loaded using182+ the *load* argument. This method passes the loaded Mapping183+ to the :meth:`from_mapping` function.184 185 :param filename: the filename of the JSON file. This can either be an186 absolute filename or a filename relative to the187 root path.188+ :param load: a callable that takes a file handle and returns a mapping189+ from the file.190+ :type load: Callable[[Reader], Mapping]. Where Reader is a Protocol191+ that implements a read method.192 :param silent: set to ``True`` if you want silent failure for missing193 files.194 190- .. versionadded:: 0.11195+ .. versionadded:: 1.2196 """197 filename = os.path.join(self.root_path, filename)193-198 try:195- with open(filename) as json_file:196- obj = json.loads(json_file.read())199+ with open(filename) as file_:200+ obj = load(file_)201 except IOError as e:202 if silent and e.errno in (errno.ENOENT, errno.EISDIR):203 return False204 e.strerror = "Unable to load configuration file (%s)" % e.strerror205 raise206 return self.from_mapping(obj)207 208+ def from_json(self, filename, silent=False):209+ """Updates the values in the config from a JSON file. This function210+ behaves as if the JSON object was a dictionary and passed to the211+ :meth:`from_mapping` function.212+213+ :param filename: the filename of the JSON file. This can either be an214+ absolute filename or a filename relative to the215+ root path.216+ :param silent: set to ``True`` if you want silent failure for missing217+ files.218+219+ .. versionadded:: 0.11220+ """221+ warnings.warn(222+ DeprecationWarning(223+ '"from_json" is deprecated and will be removed in 2.0. Use'224+ ' "from_file(filename, load=json.load)" instead.'225+ )226+ )227+ return self.from_file(filename, json.load, silent=silent)228+229 def from_mapping(self, *mapping, **kwargs):230 """Updates the config like :meth:`update` ignoring items with non-upper231 keys.232 62 unmodified linesmodified:tests/test_config.py+7 added-6 removed
4 unmodified lines5 6 :copyright: 2010 Pallets7 :license: BSD-3-Clause8 """9+import json10 import os11 import textwrap12 from datetime import timedelta13 13 unmodified lines27 assert app.config["TEST_KEY"] == "foo"28 assert "TestConfig" not in app.config29 30 30-def test_config_from_file():31+def test_config_from_pyfile():32 app = flask.Flask(__name__)33 app.config.from_pyfile(__file__.rsplit(".", 1)[0] + ".py")34 common_object_test(app)35 3 unmodified lines39 app.config.from_object(__name__)40 common_object_test(app)41 42 42-def test_config_from_json():43+def test_config_from_file():44 app = flask.Flask(__name__)45 current_dir = os.path.dirname(os.path.abspath(__file__))45- app.config.from_json(os.path.join(current_dir, "static", "config.json"))46+ app.config.from_file(os.path.join(current_dir, "static", "config.json"), json.load)47 common_object_test(app)48 49 50 def test_config_from_mapping():65 unmodified lines116 assert msg.endswith("missing.cfg'")117 assert not app.config.from_pyfile("missing.cfg", silent=True)118 119 119-def test_config_missing_json():120+def test_config_missing_file():121 app = flask.Flask(__name__)122 with pytest.raises(IOError) as e:122- app.config.from_json("missing.json")123+ app.config.from_file("missing.json", load=json.load)124 msg = str(e.value)125 assert msg.startswith(126 "[Errno 2] Unable to load configuration file (No such file or directory):"127 )128 assert msg.endswith("missing.json'")128- assert not app.config.from_json("missing.json", silent=True)129+ assert not app.config.from_file("missing.json", load=json.load, silent=True)130 131 132 def test_custom_config_class():133 class Config(flask.Config):70 unmodified lines