Explorar o código

add helper functions to pythonize environment variables and update global settings dict

Mohammed Khan hai 1 ano
pai
achega
58b2f712ff

+ 0 - 0
backend/general/__init__.py


+ 0 - 0
backend/general/utils/__init__.py


+ 20 - 0
backend/general/utils/collections.py

@@ -0,0 +1,20 @@
+def deep_update(base_dict, update_with):
+    """
+    Updates the base_dict (eg. settings/base.py settings) with the values present
+    in the update_with dict
+    """
+    # iterate over items in the update_with dict
+    for key, value in update_with.items():
+        if isinstance(value, dict):  # update_with dict value is a dict, i.e. update_with[key] = {}
+            base_dict_value = base_dict.get(key)
+
+            # check if base_dict value is also a dict
+            if isinstance(base_dict_value, dict):  # check if base_dict[key] = {}
+                deep_update(base_dict_value, value)  # recurse
+            else:
+                base_dict[key] = value  # else update the base dict with whatever dict value in update_with
+        else:
+            base_dict[key] = value
+
+    # return the updated base_dict
+    return base_dict

+ 14 - 0
backend/general/utils/misc.py

@@ -0,0 +1,14 @@
+import yaml
+
+
+def yaml_coerce(value):
+    """
+    Pass in a string dictionary and convert it into proper python dictionary
+    """
+    if isinstance(value, str):
+        # create a tiny snippet of YAML, with key=dummy, and val=value, then load the YAML into
+        # a pure Pythonic dictionary. Then, we read off the dummy key from the coversion to get our
+        # final result
+        return yaml.load(f'dummy: {value}', Loader=yaml.SafeLoader)['dummy']
+
+    return value

+ 17 - 0
backend/general/utils/settings.py

@@ -0,0 +1,17 @@
+import os
+from .misc import yaml_coerce
+
+
+def get_settings_from_environment(prefix):
+    """
+    Django settings specific to the environment (eg. production) will be stored as environment variables
+    prefixed with "PREFIX_", eg. prefix="UNTUBESETTINGS_"
+    E.G. environment variables like UNTUBESETTINGS_SECRET_KEY=123, UNTUBESETTINGS_DATABASE="{'DB': {'NAME': 'db'}}"
+    will be converted to pure Python dictionary with the prefix "UNTUBESETTINGS_" removed from the keys
+    {
+       "SECRET_KEY": 123,
+       "DB": {'NAME': 'db'}
+    }
+    """
+    prefix_len = len(prefix)
+    return {key[prefix_len:]: yaml_coerce(value) for key, value in os.environ.items() if key.startswith(prefix)}