Browse Source

Make the program respect config vars

tags/0.0.1b
Timur Demin 1 month ago
parent
commit
575b8b6953
Signed by: Timur Demin <me@tdem.in> GPG Key ID: 9EDF3F9D9286FA20
2 changed files with 28 additions and 0 deletions
  1. 4
    0
      README.md
  2. 24
    0
      project_amber/config.py

+ 4
- 0
README.md View File

@@ -19,6 +19,10 @@ Example config:
19 19
         "loglevel": 0 // 0: errors, 1: warnings, 2: info
20 20
     }
21 21
 
22
+If there are environment variables `AMBER_DATABASE` / `AMBER_ALLOW_SIGNUP` /
23
+`AMBER_LOGLEVEL` set, the program will respect them and use over the values
24
+provided with the config file.
25
+
22 26
 #### Dependencies
23 27
 
24 28
 This app directly depends on `flask`, `flask-sqlalchemy`, and `bcrypt`.

+ 24
- 0
project_amber/config.py View File

@@ -37,6 +37,30 @@ for entry in config:
37 37
     if entry in loadedConfig:
38 38
         config[entry] = loadedConfig[entry]
39 39
 
40
+def string_to_bool(val: str) -> bool:
41
+    """
42
+    Converts a string containing a bool value to Python's bool. Serves as a
43
+    helper in configuration code.
44
+    """
45
+    if val == "1" or val.lower() == "true":
46
+        return True
47
+    if val == "0" or val.lower() == "false":
48
+        return False
49
+    return False
50
+
51
+# override config with environment variables in need, the first element of a
52
+# tuple is the environment variable itself, the second is the corresponding
53
+# `config` key, and the third one is the function to convert the possible values
54
+for mapping in (
55
+    ("AMBER_DATABASE", "database", lambda val: val), # str -> str
56
+    # pylint: disable=unnecessary-lambda
57
+    ("AMBER_LOGLEVEL", "loglevel", lambda val: int(val)), # str -> int
58
+    ("AMBER_ALLOW_SIGNUP", "allow_signup", string_to_bool) # str -> bool
59
+):
60
+    env_value = os.getenv(mapping[0])
61
+    if not env_value is None:
62
+        config[mapping[1]] = mapping[2](env_value)
63
+
40 64
 if config["database"] == "":
41 65
     print("No database specified. Exiting.")
42 66
     exit(1)

Loading…
Cancel
Save