Skip to content
Myr

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

3 files+56 added−16 removed

modified:docs/config.rst+16 added-2 removed
391 unmodified lines
392393 Added :data:`MAX_COOKIE_SIZE` to control a warning from Werkzeug.394395396Configuring from Files397----------------------396Configuring from Python Files397-----------------------------398399Configuration becomes more useful if you can store it in a separate file,400ideally located outside the actual application package. This makes401packaging and distributing your application possible via various package
37 unmodified lines
439methods on the config object as well to load from individual files. For a440complete reference, read the :class:`~flask.Config` object's441documentation.442443Configuring from files444----------------------445446It is also possible to load configure from a flat file in a format of447your choice, for example to load from a TOML (or JSON) formatted448file::449450 import json451 import toml452453 app.config.from_file("config.toml", load=toml.load)454 # Alternatively, if you prefer JSON455 app.config.from_file("config.json", load=json.load)456457458Configuring from Environment Variables459--------------------------------------460461In addition to pointing to configuration files using environment variables, you
250 unmodified lines
modified:src/flask/config.py+33 added-8 removed
9 unmodified lines
10"""11import errno12import os13import types14import warnings1516from werkzeug.utils import import_string1718from . import json
157 unmodified lines
176 for key in dir(obj):177 if key.isupper():178 self[key] = getattr(obj, key)179179 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.184185 :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.194190 .. versionadded:: 0.11195 .. versionadded:: 1.2196 """197 filename = os.path.join(self.root_path, filename)193198 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)207208 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.212213 :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.218219 .. 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)228229 def from_mapping(self, *mapping, **kwargs):230 """Updates the config like :meth:`update` ignoring items with non-upper231 keys.232
62 unmodified lines
modified:tests/test_config.py+7 added-6 removed
4 unmodified lines
56 :copyright: 2010 Pallets7 :license: BSD-3-Clause8"""9import json10import os11import textwrap12from datetime import timedelta13
13 unmodified lines
27 assert app.config["TEST_KEY"] == "foo"28 assert "TestConfig" not in app.config293030def test_config_from_file():31def 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 lines
39 app.config.from_object(__name__)40 common_object_test(app)414242def test_config_from_json():43def 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)484950def test_config_from_mapping():
65 unmodified lines
116 assert msg.endswith("missing.cfg'")117 assert not app.config.from_pyfile("missing.cfg", silent=True)118119119def test_config_missing_json():120def 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)130131132def test_custom_config_class():133 class Config(flask.Config):
70 unmodified lines