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.
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
Provenance
- Commit
08a283a- Tree
7d75e44- Author
pgjones <philip.graham.jones@googlemail.com>- Committer
David Lord <davidism@gmail.com>- Parent
425a626
3 files changed+94 added−23 removed
modified:docs/config.rst+24 added-23 removed
513 unmodified lines514 515 Configuring from Environment Variables516 --------------------------------------517 518-In addition to pointing to configuration files using environment variables, you519-may find it useful (or necessary) to control your configuration values directly520-from the environment.518+In addition to pointing to configuration files using environment519+variables, you may find it useful (or necessary) to control your520+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:525 526 .. tabs::1 unmodified line528 .. group-tab:: Bash529 530 .. code-block:: text531 530- $ 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/536 537 .. group-tab:: Fish538 539 .. code-block:: text540 539- $ 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/545 546 .. group-tab:: CMD547 548 .. code-block:: text549 548- > 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/554 555 .. group-tab:: Powershell556 557 .. code-block:: text558 557- > $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/563 562-While this approach is straightforward to use, it is important to remember that563-environment variables are strings -- they are not automatically deserialized564-into Python types.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.566 566-Here is an example of a configuration file that uses environment variables::567+.. code-block:: python568 568- import os569+ app.config.from_prefixed_env()570+ app.config["SECRET_KEY"] # Is "5f352379324c22463451387a0aec5d2f"571 570- _mail_enabled = os.environ.get("MAIL_ENABLED", default="true")571- MAIL_ENABLED = _mail_enabled.lower() in {"1", "t", "true"}572+The prefix is ``FLASK_`` by default, however it is an configurable via573+the ``prefix`` argument of :meth:`~flask.Config.from_prefixed_env`.574 573- SECRET_KEY = os.environ.get("SECRET_KEY")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`.579 575- if not SECRET_KEY:576- raise ValueError("No SECRET_KEY set for Flask application")577-578-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``.583 210 unmodified linesmodified:src/flask/config.py+46 added
1 import errno2+import json3 import os4 import types5 import typing as t6 7 from werkzeug.utils import import_string8 9 10+def _json_loads(raw: t.Union[str, bytes]) -> t.Any:11+ try:12+ return json.loads(raw)13+ except json.JSONDecodeError:14+ return raw15+16+17 class ConfigAttribute:18 """Makes an attribute forward to the config"""19 20 def __init__(self, name: str, get_converter: t.Optional[t.Callable] = None) -> None:83 unmodified lines104 " file"105 )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,113+ ) -> bool:114+ """Updates the config from environment variables with the prefix.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.120+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.125+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.130+131+ :param loads: A callable that takes a str (or bytes) returns132+ the parsed value.133+ :return: Always returns ``True``.134+135+ .. versionadded:: 2.1.0136+137+ """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)143+144+ return self.from_mapping(mapping)145+146 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 linesmodified:tests/test_config.py+24 added
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):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()54+55+56+def 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()63+64+65 def 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