Merge pull request #3398 from pgjones/toml
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Support loading configuration from text files
authored by David Lord · committed by GitHub · parents 7df10cd, aac0f58 · Browse files · 4 files·+77 added−21 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+77 added−21 removed
- tests:+7 added−6 removed
- other:+70 added−15 removed
Provenance
- Commit
8f422d2- Tree
9af0bb6- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
7df10cd- Parent 2
aac0f58
4 files changed+77 added−21 removed
modified:docs/config.rst+22 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 package38 unmodified lines440 complete reference, read the :class:`~flask.Config` object's441 documentation.442 443 444+Configuring from Data Files445+---------------------------446+447+It is also possible to load configuration from a file in a format of448+your choice using :meth:`~flask.Config.from_file`. For example to load449+from a TOML file:450+451+.. code-block:: python452+453+ import toml454+ app.config.from_file("config.toml", load=toml.load)455+456+Or from a JSON file:457+458+.. code-block:: python459+460+ import json461+ app.config.from_file("config.json", load=json.load)462+463+464 Configuring from Environment Variables465 --------------------------------------466 467 In addition to pointing to configuration files using environment variables, you250 unmodified linesmodified:src/flask/config.py+45 added-13 removed
9 unmodified lines10 """11 import errno12 import os13 import types14+import warnings15 16 from werkzeug.utils import import_string17 17-from . import json18 from ._compat import iteritems19 from ._compat import string_types20 21 153 unmodified lines175 for key in dir(obj):176 if key.isupper():177 self[key] = getattr(obj, key)178 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.179+ def from_file(self, filename, load, silent=False):180+ """Update the values in the config from a file that is loaded181+ using the ``load`` parameter. The loaded data is passed to the182+ :meth:`from_mapping` method.183 184- :param filename: the filename of the JSON file. This can either be an185- absolute filename or a filename relative to the186- root path.187- :param silent: set to ``True`` if you want silent failure for missing188- files.184+ .. code-block:: python185 186+ import toml187+ app.config.from_file("config.toml", load=toml.load)188+189+ :param filename: The path to the data file. This can be an190+ absolute path or relative to the config root path.191+ :param load: A callable that takes a file handle and returns a192+ mapping of loaded data from the file.193+ :type load: ``Callable[[Reader], Mapping]`` where ``Reader``194+ implements a ``read`` method.195+ :param silent: Ignore the file if it doesn't exist.196+190- .. versionadded:: 0.11197+ .. versionadded:: 1.2198 """199 filename = os.path.join(self.root_path, filename)200 201 try:195- with open(filename) as json_file:196- obj = json.loads(json_file.read())202+ with open(filename) as f:203+ obj = load(f)204 except IOError as e:205 if silent and e.errno in (errno.ENOENT, errno.EISDIR):206 return False207+208 e.strerror = "Unable to load configuration file (%s)" % e.strerror209 raise210+211 return self.from_mapping(obj)212 213+ def from_json(self, filename, silent=False):214+ """Update the values in the config from a JSON file. The loaded215+ data is passed to the :meth:`from_mapping` method.216+217+ :param filename: The path to the JSON file. This can be an218+ absolute path or relative to the config root path.219+ :param silent: Ignore the file if it doesn't exist.220+221+ .. deprecated:: 1.2222+ Use :meth:`from_file` with :meth:`json.load` instead.223+224+ .. versionadded:: 0.11225+ """226+ warnings.warn(227+ "'from_json' is deprecated and will be removed in 2.0."228+ " Use 'from_file(filename, load=json.load)' instead.",229+ DeprecationWarning,230+ stacklevel=2,231+ )232+ from .json import load233+234+ return self.from_file(filename, load, silent=silent)235+236 def from_mapping(self, *mapping, **kwargs):237 """Updates the config like :meth:`update` ignoring items with non-upper238 keys.239 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 linesmodified:CHANGES.rst+3 added
5 unmodified lines6 Unreleased7 8 - Add :meth:`sessions.SessionInterface.get_cookie_name` to allow9 setting the session cookie name dynamically. :pr:`3369`10+- Add :meth:`Config.from_file` to load config using arbitrary file11+ loaders, such as ``toml.load`` or ``json.load``.12+ :meth:`Config.from_json` is deprecated in favor of this. :pr:`3398`13 14 15 Version 1.1.216 -------------1004 unmodified lines