Skip to content
Myr

Merge pull request #4479 from pgjones/env_config

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Allow loading of environment variables into the config

authored by David Lord · committed by GitHub · parents 425a626, e75d575 · Browse files · 4 files+190 added−30 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+190 added−30 removed

  • tests:+62 added−0 removed
  • other:+128 added−30 removed

4 files+190 added−30 removed

modified:docs/config.rst+51 added-29 removed
513 unmodified lines
514515Configuring from Environment Variables516--------------------------------------517518In addition to pointing to configuration files using environment variables, you519may find it useful (or necessary) to control your configuration values directly520from the environment.518In addition to pointing to configuration files using environment519variables, you may find it useful (or necessary) to control your520configuration 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`.523522Environment 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:: Bash530531 .. code-block:: text532530 $ export SECRET_KEY="5f352379324c22463451387a0aec5d2f"531 $ export MAIL_ENABLED=false533 $ export FLASK_SECRET_KEY="5f352379324c22463451387a0aec5d2f"534 $ export FLASK_MAIL_ENABLED=false535 $ flask run536 * Running on http://127.0.0.1:5000/537538 .. group-tab:: Fish539540 .. code-block:: text541539 $ set -x SECRET_KEY "5f352379324c22463451387a0aec5d2f"540 $ set -x MAIL_ENABLED false542 $ set -x FLASK_SECRET_KEY "5f352379324c22463451387a0aec5d2f"543 $ set -x FLASK_MAIL_ENABLED false544 $ flask run545 * Running on http://127.0.0.1:5000/546547 .. group-tab:: CMD548549 .. code-block:: text550548 > set SECRET_KEY="5f352379324c22463451387a0aec5d2f"549 > set MAIL_ENABLED=false551 > set FLASK_SECRET_KEY="5f352379324c22463451387a0aec5d2f"552 > set FLASK_MAIL_ENABLED=false553 > flask run554 * Running on http://127.0.0.1:5000/555556 .. group-tab:: Powershell557558 .. code-block:: text559557 > $env:SECRET_KEY = "5f352379324c22463451387a0aec5d2f"558 > $env:MAIL_ENABLED = "false"560 > $env:FLASK_SECRET_KEY = "5f352379324c22463451387a0aec5d2f"561 > $env:FLASK_MAIL_ENABLED = "false"562 > flask run563 * Running on http://127.0.0.1:5000/564562While this approach is straightforward to use, it is important to remember that563environment variables are strings -- they are not automatically deserialized564into Python types.565The variables can then be loaded and accessed via the config with a key566equal to the environment variable name without the prefix i.e.567566Here is an example of a configuration file that uses environment variables::568.. code-block:: python569568 import os570 app.config.from_prefixed_env()571 app.config["SECRET_KEY"] # Is "5f352379324c22463451387a0aec5d2f"572570 _mail_enabled = os.environ.get("MAIL_ENABLED", default="true")571 MAIL_ENABLED = _mail_enabled.lower() in {"1", "t", "true"}573The prefix is ``FLASK_`` by default. This is configurable via the574``prefix`` argument of :meth:`~flask.Config.from_prefixed_env`.575573 SECRET_KEY = os.environ.get("SECRET_KEY")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`.580575 if not SECRET_KEY:576 raise ValueError("No SECRET_KEY set for Flask application")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.584585It 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.588579Notice that any value besides an empty string will be interpreted as a boolean580``True`` value in Python, which requires care if an environment explicitly sets581values intended to be ``False``.589.. code-block:: text590583Make sure to load the configuration very early on, so that extensions have the584ability to access the configuration when starting up. There are other methods585on the config object as well to load from individual files. For a complete586reference, read the :class:`~flask.Config` class documentation.591 $ export FLASK_MYAPI__credentials__username=user123592593.. code-block:: python594595 app.config["MYAPI"]["credentials"]["username"] # Is "user123"596597On Windows, environment variable keys are always uppercase, therefore598the above example would end up as ``MYAPI__CREDENTIALS__USERNAME``.599600For even more config loading features, including merging and601case-insensitive Windows support, try a dedicated library such as602Dynaconf_, which includes integration with Flask.603604.. _Dynaconf: https://www.dynaconf.com/605606607Configuration Best Practices608----------------------------609610The downside with the approach mentioned earlier is that it makes testing
9 unmodified lines
6202. Do not write code that needs the configuration at import time. If you621 limit yourself to request-only accesses to the configuration you can622 reconfigure the object later on as needed.6236243. Make sure to load the configuration very early on, so that625 extensions can access the configuration when calling ``init_app``.626627628.. _config-dev-prod:629630Development / Production631------------------------
183 unmodified lines
modified:src/flask/config.py+73 added-1 removed
1import errno2import json3import os4import types5import typing as t67from werkzeug.utils import import_string8910def _json_loads(raw: t.Union[str, bytes]) -> t.Any:11 try:12 return json.loads(raw)13 except json.JSONDecodeError:14 return raw151617class ConfigAttribute:18 """Makes an attribute forward to the config"""1920 def __init__(self, name: str, get_converter: t.Optional[t.Callable] = None) -> None:
56 unmodified lines
77 :param defaults: an optional dictionary of default values78 """7980 def __init__(self, root_path: str, defaults: t.Optional[dict] = None) -> None:73 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
18 unmodified lines
104 " file"105 )106 return self.from_pyfile(rv, silent=silent)107108 def from_prefixed_env(109 self, prefix: str = "FLASK", *, loads: t.Callable[[str], t.Any] = json.loads110 ) -> bool: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 Keys are loaded in :func:`sorted` order.117118 The default loading function attempts to parse values as any119 valid JSON type, including dicts and lists.120121 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.124125 :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`.131132 .. versionadded:: 2.1133 """134 prefix = f"{prefix}_"135 len_prefix = len(prefix)136137 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+62 added
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_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__)51 app.config.from_prefixed_env()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.config606162def 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__)67 app.config.from_prefixed_env("NOT_FLASK")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 if os.name != "nt":83 assert app.config["EXIST"] == {84 "ok": "other",85 "flag": True,86 "inner": {"ik": 2},87 "new": {"more": {"k": False}},88 }89 else:90 # Windows env var keys are always uppercase.91 assert app.config["EXIST"] == {92 "ok": "value",93 "OK": "other",94 "flag": True,95 "inner": {"ik": 1},96 "INNER": {"IK": 2},97 "NEW": {"MORE": {"k": False}},98 }99100 assert app.config["NEW"] == {"K": "v"}101102103def test_config_from_mapping():104 app = flask.Flask(__name__)105 app.config.from_mapping({"SECRET_KEY": "config", "TEST_KEY": "foo"})106 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