Skip to content
Myr

Allow loading of environment variables into the config

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

This new method will pick out any environment variables with a certain prefix and place them into the config named without the prefix. This makes it easy to use environment variables to configure the app as is now more popular than when Flask started. The prefix should ensure that the environment isn't polluted and the config isn't polluted by environment variables. I've followed the dynaconf convention of trying to parse the environment variable and then falling back to the raw value if parsing fails.

authored by pgjones · committed by David Lord · parent 425a626 · Browse files · 3 files+94 added−23 removed
This commit

State

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

Diff stats

3 files+94 added−23 removed

  • tests:+24 added−0 removed
  • other:+70 added−23 removed

3 files+94 added−23 removed

modified:docs/config.rst+24 added-23 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`.523524Environment variables can be set in the shell before starting the server:525526.. tabs::
1 unmodified line
528 .. group-tab:: Bash529530 .. code-block:: text531530 $ export SECRET_KEY="5f352379324c22463451387a0aec5d2f"531 $ export MAIL_ENABLED=false532 $ export FLASK_SECRET_KEY="5f352379324c22463451387a0aec5d2f"533 $ export FLASK_MAIL_ENABLED=false534 $ flask run535 * Running on http://127.0.0.1:5000/536537 .. group-tab:: Fish538539 .. code-block:: text540539 $ set -x SECRET_KEY "5f352379324c22463451387a0aec5d2f"540 $ set -x MAIL_ENABLED false541 $ set -x FLASK_SECRET_KEY "5f352379324c22463451387a0aec5d2f"542 $ set -x FLASK_MAIL_ENABLED false543 $ flask run544 * Running on http://127.0.0.1:5000/545546 .. group-tab:: CMD547548 .. code-block:: text549548 > set SECRET_KEY="5f352379324c22463451387a0aec5d2f"549 > set MAIL_ENABLED=false550 > set FLASK_SECRET_KEY="5f352379324c22463451387a0aec5d2f"551 > set FLASK_MAIL_ENABLED=false552 > flask run553 * Running on http://127.0.0.1:5000/554555 .. group-tab:: Powershell556557 .. code-block:: text558557 > $env:SECRET_KEY = "5f352379324c22463451387a0aec5d2f"558 > $env:MAIL_ENABLED = "false"559 > $env:FLASK_SECRET_KEY = "5f352379324c22463451387a0aec5d2f"560 > $env:FLASK_MAIL_ENABLED = "false"561 > flask run562 * Running on http://127.0.0.1:5000/563562While this approach is straightforward to use, it is important to remember that563environment variables are strings -- they are not automatically deserialized564into Python types.564The variables can then be loaded and accessed via the config with a565key equal to the environment variable name without the prefix i.e.566566Here is an example of a configuration file that uses environment variables::567.. code-block:: python568568 import os569 app.config.from_prefixed_env()570 app.config["SECRET_KEY"] # Is "5f352379324c22463451387a0aec5d2f"571570 _mail_enabled = os.environ.get("MAIL_ENABLED", default="true")571 MAIL_ENABLED = _mail_enabled.lower() in {"1", "t", "true"}572The prefix is ``FLASK_`` by default, however it is an configurable via573the ``prefix`` argument of :meth:`~flask.Config.from_prefixed_env`.574573 SECRET_KEY = os.environ.get("SECRET_KEY")575Whilst 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`.579575 if not SECRET_KEY:576 raise ValueError("No SECRET_KEY set for Flask application")577578580Notice 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``.583
210 unmodified lines
modified:src/flask/config.py+46 added
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:
83 unmodified lines
104 " file"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,113 ) -> bool:114 """Updates the config from environment variables with the prefix.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.120121 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.125126 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.130131 :param loads: A callable that takes a str (or bytes) returns132 the parsed value.133 :return: Always returns ``True``.134135 .. versionadded:: 2.1.0136137 """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)143144 return self.from_mapping(mapping)145146 def from_pyfile(self, filename: str, silent: bool = False) -> bool:147 """Updates the values in the config from a Python file. This function148 behaves as if the file was imported as module with the149 :meth:`from_object` function.
169 unmodified lines
modified:tests/test_config.py+24 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_config_from_prefixed_env(monkeypatch):42 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")48 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()545556def test_config_from_custom_prefixed_env(monkeypatch):57 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_")61 assert app.config["A"] == "Another value"62 assert "A value" not in app.config.items()636465def test_config_from_mapping():66 app = flask.Flask(__name__)67 app.config.from_mapping({"SECRET_KEY": "config", "TEST_KEY": "foo"})68 common_object_test(app)
146 unmodified lines