Skip to content
Myr

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

4 files+77 added−21 removed

modified:docs/config.rst+22 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
38 unmodified lines
440complete reference, read the :class:`~flask.Config` object's441documentation.442443444Configuring from Data Files445---------------------------446447It is also possible to load configuration from a file in a format of448your choice using :meth:`~flask.Config.from_file`. For example to load449from a TOML file:450451.. code-block:: python452453 import toml454 app.config.from_file("config.toml", load=toml.load)455456Or from a JSON file:457458.. code-block:: python459460 import json461 app.config.from_file("config.json", load=json.load)462463464Configuring from Environment Variables465--------------------------------------466467In addition to pointing to configuration files using environment variables, you
250 unmodified lines
modified:src/flask/config.py+45 added-13 removed
9 unmodified lines
10"""11import errno12import os13import types14import warnings1516from werkzeug.utils import import_string1717from . import json18from ._compat import iteritems19from ._compat import string_types2021
153 unmodified lines
175 for key in dir(obj):176 if key.isupper():177 self[key] = getattr(obj, key)178179 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.183184 :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:: python185186 import toml187 app.config.from_file("config.toml", load=toml.load)188189 :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.196190 .. versionadded:: 0.11197 .. versionadded:: 1.2198 """199 filename = os.path.join(self.root_path, filename)200201 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 False207208 e.strerror = "Unable to load configuration file (%s)" % e.strerror209 raise210211 return self.from_mapping(obj)212213 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.216217 :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.220221 .. deprecated:: 1.2222 Use :meth:`from_file` with :meth:`json.load` instead.223224 .. 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 load233234 return self.from_file(filename, load, silent=silent)235236 def from_mapping(self, *mapping, **kwargs):237 """Updates the config like :meth:`update` ignoring items with non-upper238 keys.239
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
modified:CHANGES.rst+3 added
5 unmodified lines
6Unreleased78- 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`131415Version 1.1.216-------------
1004 unmodified lines