1+ import json
2+ from os import path
3+ from schema import Schema , SchemaError
4+
5+ class Config (object ):
6+
7+ __instance = None
8+
9+ def __new__ (cls ,schema :dict = None , path_file :str = "config.json" ):
10+ if cls .__instance is None :
11+ cls .__create_new_instace (schema , path_file )
12+ return cls .__instance
13+
14+ @classmethod
15+ def __create_new_instace (cls ,schema :dict , path_file :str ):
16+ if not path .isfile (path_file ):
17+ raise ConfigException ("Wasn't possible find the config file: {}" .format (path_file ))
18+
19+ with open (path_file , "r" ) as f :
20+ file_buff = f .read ()
21+ f .close ()
22+
23+ try :
24+ config = Schema (schema ).validate (json .loads (file_buff ))
25+ if not isinstance (config , dict ):
26+ raise ConfigException ("The first element's config should be a Map" )
27+ cls .__instance = cls .__dict_2_obj (config )
28+ except json .JSONDecodeError :
29+ raise ConfigException ("{}" .format ("Wasn't possible to decode the json file:{}" .format (path_file )))
30+ except SchemaError as e :
31+ raise ConfigException (str (e ))
32+
33+ @classmethod
34+ def __dict_2_obj (cls , data :dict ):
35+ _type = type (data )
36+
37+ if _type is dict :
38+ obj = object .__new__ (cls )
39+ for key in data :
40+ sub_data = data [key ]
41+ if type (sub_data ) in (list , dict ):
42+ setattr (obj , key , cls .__dict_2_obj (sub_data ))
43+ else :
44+ setattr (obj , key , sub_data )
45+ return obj
46+ if _type is list :
47+ for i in range (len (data )):
48+ data [i ] = cls .__dict_2_obj (data [i ])
49+ return data
50+ else :
51+ return data
52+
53+ class ConfigException (Exception ):
54+ def __init__ (self , * args , ** kwargs ):
55+ super ().__init__ (* args , ** kwargs )
0 commit comments