Skip to content
Myr

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

4 files+136 added−62 removed

modified:docs/config.rst+34 added-16 removed
519 unmodified lines
520configuration values directly from the environment. Flask can be521instructed to load all environment variables starting with a specific522prefix into the config using :meth:`~flask.Config.from_prefixed_env`.523524Environment variables can be set in the shell before starting the server:524Environment variables can be set in the shell before starting the525server:526527.. tabs::528529 .. group-tab:: Bash
31 unmodified lines
561 > $env:FLASK_MAIL_ENABLED = "false"562 > flask run563 * Running on http://127.0.0.1:5000/564564The variables can then be loaded and accessed via the config with a565key equal to the environment variable name without the prefix i.e.565The variables can then be loaded and accessed via the config with a key566equal to the environment variable name without the prefix i.e.567568.. code-block:: python569570 app.config.from_prefixed_env()571 app.config["SECRET_KEY"] # Is "5f352379324c22463451387a0aec5d2f"572572The prefix is ``FLASK_`` by default, however it is an configurable via573the ``prefix`` argument of :meth:`~flask.Config.from_prefixed_env`.573The prefix is ``FLASK_`` by default. This is configurable via the574``prefix`` argument of :meth:`~flask.Config.from_prefixed_env`.575575Whilst the value of any environment variable is a string, it will be576parsed before being placed into the flask config. By default the577parsing is done by json.loads, however this is configurable via the578``loads`` argument of :meth:`~flask.Config.from_prefixed_env`.576Values will be parsed to attempt to convert them to a more specific type577than strings. By default :func:`json.loads` is used, so any valid JSON578value is possible, including lists and dicts. This is configurable via579the ``loads`` argument of :meth:`~flask.Config.from_prefixed_env`.580580Notice that any value besides an empty string will be interpreted as a boolean581``True`` value in Python, which requires care if an environment explicitly sets582values intended to be ``False``.581When adding a boolean value with the default JSON parsing, only "true"582and "false", lowercase, are valid values. Keep in mind that any583non-empty string is considered ``True`` by Python.584584Make sure to load the configuration very early on, so that extensions have the585ability to access the configuration when starting up. There are other methods586on the config object as well to load from individual files. For a complete587reference, read the :class:`~flask.Config` class documentation.585It is possible to set keys in nested dictionaries by separating the586keys with double underscore (``__``). Any intermediate keys that don't587exist on the parent dict will be initialized to an empty dict.588589.. code-block:: text590591 $ export FLASK_MYAPI__credentials__username=user123592593.. code-block:: python594595 app.config["MYAPI"]["credentials"]["username"] # Is "user123"596597For even more config loading features, including merging, try a598dedicated library such as Dynaconf_, which includes integration with599Flask.600601.. _Dynaconf: https://www.dynaconf.com/602603604Configuration Best Practices605----------------------------606607The downside with the approach mentioned earlier is that it makes testing
9 unmodified lines
6172. 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.6206213. Make sure to load the configuration very early on, so that622 extensions can access the configuration when calling ``init_app``.623624625.. _config-dev-prod:626627Development / Production628------------------------
183 unmodified lines
modified:src/flask/config.py+55 added-29 removed
76 unmodified lines
77 :param defaults: an optional dictionary of default values78 """7980 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_path8384 def from_envvar(self, variable_name: str, silent: bool = False) -> bool:85 """Loads a configuration from an environment variable pointing to
19 unmodified lines
105 )106 return self.from_pyfile(rv, silent=silent)107108 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.115116 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.117121 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.120126 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.124131 :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`.131135 .. versionadded:: 2.1.0136132 .. 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)136144 return self.from_mapping(mapping)137 for key in sorted(os.environ):138 if not key.startswith(prefix):139 continue140141 value = os.environ[key]142143 try:144 value = loads(value)145 except Exception:146 # Keep the value as a string if loading failed.147 pass148149 # Change to key.removeprefix(prefix) on Python >= 3.9.150 key = key[len_prefix:]151152 if "__" not in key:153 # A non-nested key, set directly.154 self[key] = value155 continue156157 # Traverse nested dictionaries with keys separated by "__".158 current = self159 *parts, tail = key.split("__")160161 for part in parts:162 # If an intermediate dict does not exist, create it.163 if part not in current:164 current[part] = {}165166 current = current[part]167168 current[tail] = value169170 return True171172 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 lines
modified:tests/test_config.py+43 added-17 removed
36 unmodified lines
37 app.config.from_file(os.path.join(current_dir, "static", "config.json"), json.load)38 common_object_test(app)394041def test_config_from_prefixed_env(monkeypatch):41def 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")4950 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()5253 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.config6056def test_config_from_custom_prefixed_env(monkeypatch):6162def test_from_prefixed_env_custom_prefix(monkeypatch):63 monkeypatch.setenv("FLASK_A", "a")64 monkeypatch.setenv("NOT_FLASK_A", "b")6566 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()6869 assert app.config["A"] == "b"707172def 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")7778 app = flask.Flask(__name__)79 app.config["EXIST"] = {"ok": "value", "flag": True, "inner": {"ik": 1}}80 app.config.from_prefixed_env()8182 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"}899091def 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 lines
modified:CHANGES.rst+4 added
53 unmodified lines
54 ``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`626364Version 2.0.365-------------
1199 unmodified lines