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
Provenance
- Commit
2f5a2ab- Tree
66c882b- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
425a626- Parent 2
e75d575
4 files changed+190 added−30 removed
modified:docs/config.rst+51 added-29 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 522-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:: Bash530 531 .. code-block:: text532 530- $ 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/537 538 .. group-tab:: Fish539 540 .. code-block:: text541 539- $ 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/546 547 .. group-tab:: CMD548 549 .. code-block:: text550 548- > 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/555 556 .. group-tab:: Powershell557 558 .. code-block:: text559 557- > $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/564 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.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 566-Here is an example of a configuration file that uses environment variables::568+.. code-block:: python569 568- import os570+ app.config.from_prefixed_env()571+ app.config["SECRET_KEY"] # Is "5f352379324c22463451387a0aec5d2f"572 570- _mail_enabled = os.environ.get("MAIL_ENABLED", default="true")571- MAIL_ENABLED = _mail_enabled.lower() in {"1", "t", "true"}573+The prefix is ``FLASK_`` by default. This is configurable via the574+``prefix`` argument of :meth:`~flask.Config.from_prefixed_env`.575 573- SECRET_KEY = os.environ.get("SECRET_KEY")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 575- if not SECRET_KEY:576- raise ValueError("No SECRET_KEY set for Flask application")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 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 579-Notice that any value besides an empty string will be interpreted as a boolean580-``True`` value in Python, which requires care if an environment explicitly sets581-values intended to be ``False``.589+.. code-block:: text590 583-Make sure to load the configuration very early on, so that extensions have the584-ability to access the configuration when starting up. There are other methods585-on the config object as well to load from individual files. For a complete586-reference, read the :class:`~flask.Config` class documentation.591+ $ export FLASK_MYAPI__credentials__username=user123592 593+.. code-block:: python594 595+ app.config["MYAPI"]["credentials"]["username"] # Is "user123"596+597+On Windows, environment variable keys are always uppercase, therefore598+the above example would end up as ``MYAPI__CREDENTIALS__USERNAME``.599+600+For even more config loading features, including merging and601+case-insensitive Windows support, try a dedicated library such as602+Dynaconf_, which includes integration with Flask.603+604+.. _Dynaconf: https://www.dynaconf.com/605+606+607 Configuration Best Practices608 ----------------------------609 610 The downside with the approach mentioned earlier is that it makes testing9 unmodified lines620 2. 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.623 624+3. Make sure to load the configuration very early on, so that625+ extensions can access the configuration when calling ``init_app``.626+627+628 .. _config-dev-prod:629 630 Development / Production631 ------------------------183 unmodified linesmodified:src/flask/config.py+73 added-1 removed
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:56 unmodified lines77 :param defaults: an optional dictionary of default values78 """79 80 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_path83 84 def from_envvar(self, variable_name: str, silent: bool = False) -> bool:85 """Loads a configuration from an environment variable pointing to18 unmodified lines104 " file"105 )106 return self.from_pyfile(rv, silent=silent)107 108+ 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.115+116+ Keys are loaded in :func:`sorted` order.117+118+ The default loading function attempts to parse values as any119+ valid JSON type, including dicts and lists.120+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+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+132+ .. versionadded:: 2.1133+ """134+ prefix = f"{prefix}_"135+ len_prefix = len(prefix)136+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+62 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_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__)51+ app.config.from_prefixed_env()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+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__)67+ app.config.from_prefixed_env("NOT_FLASK")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+ 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+ }99+100+ assert app.config["NEW"] == {"K": "v"}101+102+103 def 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 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