Allow loading of environment variables into the config

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 is contained in:
pgjones 2022-03-08 21:40:48 +00:00 committed by David Lord
parent 425a62686f
commit 08a283af5e
No known key found for this signature in database
GPG key ID: 7A1C87E3F5BC42A8
3 changed files with 94 additions and 23 deletions

View file

@ -38,6 +38,30 @@ def test_config_from_file():
common_object_test(app)
def test_config_from_prefixed_env(monkeypatch):
app = flask.Flask(__name__)
monkeypatch.setenv("FLASK_A", "A value")
monkeypatch.setenv("FLASK_B", "true")
monkeypatch.setenv("FLASK_C", "1")
monkeypatch.setenv("FLASK_D", "1.2")
monkeypatch.setenv("NOT_FLASK_A", "Another value")
app.config.from_prefixed_env()
assert app.config["A"] == "A value"
assert app.config["B"] is True
assert app.config["C"] == 1
assert app.config["D"] == 1.2
assert "Another value" not in app.config.items()
def test_config_from_custom_prefixed_env(monkeypatch):
app = flask.Flask(__name__)
monkeypatch.setenv("FLASK_A", "A value")
monkeypatch.setenv("NOT_FLASK_A", "Another value")
app.config.from_prefixed_env("NOT_FLASK_")
assert app.config["A"] == "Another value"
assert "A value" not in app.config.items()
def test_config_from_mapping():
app = flask.Flask(__name__)
app.config.from_mapping({"SECRET_KEY": "config", "TEST_KEY": "foo"})