From 575b8b69538288c420c4a431789fe49cf4e9eb4b Mon Sep 17 00:00:00 2001 From: Timur Demin Date: Thu, 13 Jun 2019 23:51:19 +0500 Subject: [PATCH] Make the program respect config vars --- README.md | 4 ++++ project_amber/config.py | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/README.md b/README.md index 255bf71..ef8b5c0 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,10 @@ Example config: "loglevel": 0 // 0: errors, 1: warnings, 2: info } +If there are environment variables `AMBER_DATABASE` / `AMBER_ALLOW_SIGNUP` / +`AMBER_LOGLEVEL` set, the program will respect them and use over the values +provided with the config file. + #### Dependencies This app directly depends on `flask`, `flask-sqlalchemy`, and `bcrypt`. diff --git a/project_amber/config.py b/project_amber/config.py index 56fc799..cbd9e67 100644 --- a/project_amber/config.py +++ b/project_amber/config.py @@ -37,6 +37,30 @@ if entry in loadedConfig: config[entry] = loadedConfig[entry] +def string_to_bool(val: str) -> bool: + """ + Converts a string containing a bool value to Python's bool. Serves as a + helper in configuration code. + """ + if val == "1" or val.lower() == "true": + return True + if val == "0" or val.lower() == "false": + return False + return False + +# override config with environment variables in need, the first element of a +# tuple is the environment variable itself, the second is the corresponding +# `config` key, and the third one is the function to convert the possible values +for mapping in ( + ("AMBER_DATABASE", "database", lambda val: val), # str -> str + # pylint: disable=unnecessary-lambda + ("AMBER_LOGLEVEL", "loglevel", lambda val: int(val)), # str -> int + ("AMBER_ALLOW_SIGNUP", "allow_signup", string_to_bool) # str -> bool +): + env_value = os.getenv(mapping[0]) + if not env_value is None: + config[mapping[1]] = mapping[2](env_value) + if config["database"] == "": print("No database specified. Exiting.") exit(1)