11"""Module to read yaml or json conf"""
22import logging
33import os
4- from typing import Text
54
65import anyconfig
76
109
1110logger = logging .getLogger (LOGGER_NAME )
1211
12+ config_cache = {}
13+
1314
1415class ConfFile (dict ):
1516 """Recursive get configuration from dictionary, a config file in JSON or YAML format from a path or
@@ -18,8 +19,9 @@ class ConfFile(dict):
1819 * empty_init: Allow blank variables
1920 * default_file: search for config.yml file
2021 """
21- empty_init = False
22- default_file = "config.yml"
22+ _empty_init = False
23+ _default_file = "config.yml"
24+ __path = None
2325
2426 def __init__ (self , * args , ** kwargs ):
2527 """
@@ -32,31 +34,38 @@ def __init__(self, *args, **kwargs):
3234 self[key] = getattr(obj, key)
3335 ```
3436 """
35- self .empty_init = kwargs .get ("empty_init" , False )
37+ self ._empty_init = kwargs .get ("empty_init" , False )
3638 config = kwargs .get ("config" )
37- uppercase = kwargs .get ("uppercase" , True )
3839 if config is None :
39- config = self ._get_conf_from_file (kwargs .get ("path" )) or self ._get_conf_from_env ()
40+ self .set_path (kwargs .get ("path" ))
41+ config = self ._get_conf_from_file () or self ._get_conf_from_env ()
4042
4143 if not config :
42- if self .empty_init :
44+ if self ._empty_init :
4345 config = {}
4446 else :
4547 raise ConfigDoesNotFoundException ("Configuration file not found" )
4648
49+ config = self .set_config (config )
50+
51+ super (ConfFile , self ).__init__ (config )
52+
53+ def set_path (self , path ):
54+ self .__path = path
55+
56+ def to_flask (self ):
57+ return ConfFile (config = {k .upper (): v for k , v in self .items ()})
58+
59+ def set_config (self , config ):
4760 config = dict (self .normalize_config (config ))
4861 for k , v in config .items ():
4962 setattr (self , k , v )
50- # Flask search for uppercase keys
51- if uppercase :
52- setattr (self , k .upper (), v )
53-
54- super (ConfFile , self ).__init__ (config )
63+ return config
5564
5665 def normalize_config (self , config ):
5766 for key , item in config .items ():
5867 if isinstance (item , dict ):
59- item = ConfFile (config = item , empty_init = self .empty_init )
68+ item = ConfFile (config = item , empty_init = self ._empty_init )
6069 yield self .normalize_keys (key ), item
6170
6271 @staticmethod
@@ -78,22 +87,32 @@ def __getattr__(self, name, *args, **kwargs):
7887 aux_dict = aux_dict [k ]
7988 return aux_dict
8089 except KeyError :
81- if self .empty_init :
82- return ConfFile (config = {}, empty_init = self .empty_init )
90+ if self ._empty_init :
91+ return ConfFile (config = {}, empty_init = self ._empty_init )
8392 raise AttrDoesNotExistException ("Variable {} not exist in the config file" .format (name ))
8493
8594 def _get_conf_from_env (self ):
86- config_file = os .environ .get (CONFIGMAP_FILE_ENVIRONMENT , self .default_file )
95+ config_file = os .environ .get (CONFIGMAP_FILE_ENVIRONMENT , self ._default_file )
8796 logger .debug ("[CONF] Searching file in ENV[{}]: {}..." .format (CONFIGMAP_FILE_ENVIRONMENT , config_file ))
88- return self ._get_conf_from_file (config_file )
97+ self .set_path (config_file )
98+ return self ._get_conf_from_file ()
8999
90- @ staticmethod
91- def _get_conf_from_file ( path : Text ) -> dict :
92- if not path or not os . path . isfile ( path ):
100+ def _get_conf_from_file ( self ) -> dict :
101+ if not self . __path or not os . path . isfile ( self . __path ) :
102+ logger . debug ( "[CONF] Configmap {} NOT FOUND" . format ( self . __path ))
93103 return {}
94- logger .debug ("[CONF] Configmap {} found" .format (path ))
95- conf = anyconfig .load (path )
96- return conf
104+ if self .__path not in config_cache :
105+ logger .debug ("[CONF] Configmap {} found" .format (self .__path ))
106+ config_cache [self .__path ] = anyconfig .load (self .__path )
107+ return config_cache [self .__path ]
108+
109+ def load (self ):
110+ config_src = self ._get_conf_from_file () or self ._get_conf_from_env ()
111+ self .set_config (config_src )
112+
113+ def reload (self ):
114+ config_cache .pop (self .__path , None )
115+ self .load ()
97116
98117 def __setattr__ (self , name , value , * args , ** kwargs ):
99118 super (ConfFile , self ).__setattr__ (name , value )
0 commit comments