more from_prefixed_env features
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* support nested dict access with "__" separator * don't specify separator in prefix * catch exceptions for any loads function
authored by David Lord · committed by David Lord · parent 08a283a · Browse files · 4 files·+136 added−62 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+136 added−62 removed
- tests:+43 added−17 removed
- other:+93 added−45 removed
Provenance
- Commit
4eb5e94- Tree
f020b74- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
08a283a
4 files changed+136 added−62 removed
modified:docs/config.rst+34 added-16 removed
519 unmodified lines520 configuration values directly from the environment. Flask can be521 instructed to load all environment variables starting with a specific522 prefix into the config using :meth:`~flask.Config.from_prefixed_env`.523 524-Environment variables can be set in the shell before starting the server:524+Environment variables can be set in the shell before starting the525+server:526 527 .. tabs::528 529 .. group-tab:: Bash31 unmodified lines561 > $env:FLASK_MAIL_ENABLED = "false"562 > flask run563 * Running on http://127.0.0.1:5000/564 564-The variables can then be loaded and accessed via the config with a565-key equal to the environment variable name without the prefix i.e.565+The variables can then be loaded and accessed via the config with a key566+equal to the environment variable name without the prefix i.e.567 568 .. code-block:: python569 570 app.config.from_prefixed_env()571 app.config["SECRET_KEY"] # Is "5f352379324c22463451387a0aec5d2f"572 572-The prefix is ``FLASK_`` by default, however it is an configurable via573-the ``prefix`` argument of :meth:`~flask.Config.from_prefixed_env`.573+The prefix is ``FLASK_`` by default. This is configurable via the574+``prefix`` argument of :meth:`~flask.Config.from_prefixed_env`.575 575-Whilst the value of any environment variable is a string, it will be576-parsed before being placed into the flask config. By default the577-parsing is done by json.loads, however this is configurable via the578-``loads`` argument of :meth:`~flask.Config.from_prefixed_env`.576+Values will be parsed to attempt to convert them to a more specific type577+than strings. By default :func:`json.loads` is used, so any valid JSON578+value is possible, including lists and dicts. This is configurable via579+the ``loads`` argument of :meth:`~flask.Config.from_prefixed_env`.580 580-Notice that any value besides an empty string will be interpreted as a boolean581-``True`` value in Python, which requires care if an environment explicitly sets582-values intended to be ``False``.581+When adding a boolean value with the default JSON parsing, only "true"582+and "false", lowercase, are valid values. Keep in mind that any583+non-empty string is considered ``True`` by Python.584 584-Make sure to load the configuration very early on, so that extensions have the585-ability to access the configuration when starting up. There are other methods586-on the config object as well to load from individual files. For a complete587-reference, read the :class:`~flask.Config` class documentation.585+It is possible to set keys in nested dictionaries by separating the586+keys with double underscore (``__``). Any intermediate keys that don't587+exist on the parent dict will be initialized to an empty dict.588 589+.. code-block:: text590 591+ $ export FLASK_MYAPI__credentials__username=user123592+593+.. code-block:: python594+595+ app.config["MYAPI"]["credentials"]["username"] # Is "user123"596+597+For even more config loading features, including merging, try a598+dedicated library such as Dynaconf_, which includes integration with599+Flask.600+601+.. _Dynaconf: https://www.dynaconf.com/602+603+604 Configuration Best Practices605 ----------------------------606 607 The downside with the approach mentioned earlier is that it makes testing9 unmodified lines617 2. Do not write code that needs the configuration at import time. If you618 limit yourself to request-only accesses to the configuration you can619 reconfigure the object later on as needed.620 621+3. Make sure to load the configuration very early on, so that622+ extensions can access the configuration when calling ``init_app``.623+624+625 .. _config-dev-prod:626 627 Development / Production628 ------------------------183 unmodified linesmodified:src/flask/config.py+55 added-29 removed
76 unmodified lines77 :param defaults: an optional dictionary of default values78 """79 80 def __init__(self, root_path: str, defaults: t.Optional[dict] = None) -> None:81- dict.__init__(self, defaults or {})81+ super().__init__(defaults or {})82 self.root_path = root_path83 84 def from_envvar(self, variable_name: str, silent: bool = False) -> bool:85 """Loads a configuration from an environment variable pointing to19 unmodified lines105 )106 return self.from_pyfile(rv, silent=silent)107 108 def from_prefixed_env(109- self,110- prefix: str = "FLASK_",111- *,112- loads: t.Callable[[t.Union[str, bytes]], t.Any] = _json_loads,109+ self, prefix: str = "FLASK", *, loads: t.Callable[[str], t.Any] = json.loads110 ) -> bool:114- """Updates the config from environment variables with the prefix.111+ """Load any environment variables that start with ``FLASK_``,112+ dropping the prefix from the env key for the config key. Values113+ are passed through a loading function to attempt to convert them114+ to more specific types than strings.115 116- Calling this method will result in every environment variable117- starting with **prefix** being placed into the configuration118- without the **prefix**. The prefix is configurable as an119- argument. Note that this method updates the existing config.116+ Keys are loaded in :func:`sorted` order.117 121- For example if there is an environment variable122- ``FLASK_SECRET_KEY`` with value ``secretly`` and the prefix is123- ``FLASK_`` the config will contain the key ``SECRET_KEY`` with124- the value ``secretly`` after calling this method.118+ The default loading function attempts to parse values as any119+ valid JSON type, including dicts and lists.120 126- The value of the environment variable will be passed to the127- **loads** parameter before being placed into the config. By128- default **loads** utilises the stdlib json.loads to parse the129- value, falling back to the value itself on parsing error.121+ Specific items in nested dicts can be set by separating the122+ keys with double underscores (``__``). If an intermediate key123+ doesn't exist, it will be initialized to an empty dict.124 131- :param loads: A callable that takes a str (or bytes) returns132- the parsed value.133- :return: Always returns ``True``.125+ :param prefix: Load env vars that start with this prefix,126+ separated with an underscore (``_``).127+ :param loads: Pass each string value to this function and use128+ the returned value as the config value. If any error is129+ raised it is ignored and the value remains a string. The130+ default is :func:`json.loads`.131 135- .. versionadded:: 2.1.0136-132+ .. versionadded:: 2.1133 """138- mapping = {}139- for raw_key, value in os.environ.items():140- if raw_key.startswith(prefix):141- key = raw_key[len(prefix) :] # Use removeprefix with Python 3.9142- mapping[key] = loads(value)134+ prefix = f"{prefix}_"135+ len_prefix = len(prefix)136 144- return self.from_mapping(mapping)137+ for key in sorted(os.environ):138+ if not key.startswith(prefix):139+ continue140 141+ value = os.environ[key]142+143+ try:144+ value = loads(value)145+ except Exception:146+ # Keep the value as a string if loading failed.147+ pass148+149+ # Change to key.removeprefix(prefix) on Python >= 3.9.150+ key = key[len_prefix:]151+152+ if "__" not in key:153+ # A non-nested key, set directly.154+ self[key] = value155+ continue156+157+ # Traverse nested dictionaries with keys separated by "__".158+ current = self159+ *parts, tail = key.split("__")160+161+ for part in parts:162+ # If an intermediate dict does not exist, create it.163+ if part not in current:164+ current[part] = {}165+166+ current = current[part]167+168+ current[tail] = value169+170+ return True171+172 def from_pyfile(self, filename: str, silent: bool = False) -> bool:173 """Updates the values in the config from a Python file. This function174 behaves as if the file was imported as module with the175 :meth:`from_object` function.169 unmodified linesmodified:tests/test_config.py+43 added-17 removed
36 unmodified lines37 app.config.from_file(os.path.join(current_dir, "static", "config.json"), json.load)38 common_object_test(app)39 40 41-def test_config_from_prefixed_env(monkeypatch):41+def test_from_prefixed_env(monkeypatch):42+ monkeypatch.setenv("FLASK_STRING", "value")43+ monkeypatch.setenv("FLASK_BOOL", "true")44+ monkeypatch.setenv("FLASK_INT", "1")45+ monkeypatch.setenv("FLASK_FLOAT", "1.2")46+ monkeypatch.setenv("FLASK_LIST", "[1, 2]")47+ monkeypatch.setenv("FLASK_DICT", '{"k": "v"}')48+ monkeypatch.setenv("NOT_FLASK_OTHER", "other")49+50 app = flask.Flask(__name__)43- monkeypatch.setenv("FLASK_A", "A value")44- monkeypatch.setenv("FLASK_B", "true")45- monkeypatch.setenv("FLASK_C", "1")46- monkeypatch.setenv("FLASK_D", "1.2")47- monkeypatch.setenv("NOT_FLASK_A", "Another value")51 app.config.from_prefixed_env()49- assert app.config["A"] == "A value"50- assert app.config["B"] is True51- assert app.config["C"] == 152- assert app.config["D"] == 1.253- assert "Another value" not in app.config.items()52 53+ assert app.config["STRING"] == "value"54+ assert app.config["BOOL"] is True55+ assert app.config["INT"] == 156+ assert app.config["FLOAT"] == 1.257+ assert app.config["LIST"] == [1, 2]58+ assert app.config["DICT"] == {"k": "v"}59+ assert "OTHER" not in app.config60 56-def test_config_from_custom_prefixed_env(monkeypatch):61+62+def test_from_prefixed_env_custom_prefix(monkeypatch):63+ monkeypatch.setenv("FLASK_A", "a")64+ monkeypatch.setenv("NOT_FLASK_A", "b")65+66 app = flask.Flask(__name__)58- monkeypatch.setenv("FLASK_A", "A value")59- monkeypatch.setenv("NOT_FLASK_A", "Another value")60- app.config.from_prefixed_env("NOT_FLASK_")67+ app.config.from_prefixed_env("NOT_FLASK")61- assert app.config["A"] == "Another value"62- assert "A value" not in app.config.items()68 69+ assert app.config["A"] == "b"70 71+72+def test_from_prefixed_env_nested(monkeypatch):73+ monkeypatch.setenv("FLASK_EXIST__ok", "other")74+ monkeypatch.setenv("FLASK_EXIST__inner__ik", "2")75+ monkeypatch.setenv("FLASK_EXIST__new__more", '{"k": false}')76+ monkeypatch.setenv("FLASK_NEW__K", "v")77+78+ app = flask.Flask(__name__)79+ app.config["EXIST"] = {"ok": "value", "flag": True, "inner": {"ik": 1}}80+ app.config.from_prefixed_env()81+82+ assert app.config["EXIST"] == {83+ "ok": "other",84+ "flag": True,85+ "inner": {"ik": 2},86+ "new": {"more": {"k": False}},87+ }88+ assert app.config["NEW"] == {"K": "v"}89+90+91 def test_config_from_mapping():92 app = flask.Flask(__name__)93 app.config.from_mapping({"SECRET_KEY": "config", "TEST_KEY": "foo"})94 common_object_test(app)146 unmodified linesmodified:CHANGES.rst+4 added
53 unmodified lines54 ``ExitStack``. :issue:`4474`55 - From Werkzeug, for redirect responses the ``Location`` header URL56 will remain relative, and exclude the scheme and domain, by default.57 :pr:`4496`58+- Add ``Config.from_prefixed_env()`` to load config values from59+ environment variables that start with ``FLASK_`` or another prefix.60+ This parses values as JSON by default, and allows setting keys in61+ nested dicts. :pr:`4479`62 63 64 Version 2.0.365 -------------1199 unmodified lines