1+ from schema import Schema , SchemaError
2+ from typing import Any
3+ from os import path
4+ import json
5+ import yaml
16import os
27import re
3- import yaml
4- import json
5- from os import path
6- from typing import Any
7- from schema import Schema , SchemaError
8-
9-
10- ENTITY_NAME_PATTERN = '^[\w\d_]+$'
118
129
1310def json_parser (file_buff ):
@@ -25,18 +22,31 @@ def yaml_parser(file_buff):
2522
2623
2724DEFAULT_CONFIG_FILES = ('config.json' , 'config.yaml' , 'config.yml' )
28-
25+ ENTITY_NAME_PATTERN = '^[\w\d_]+$'
2926SUPPORTED_EXTENSIONS = {
3027 'json' : json_parser ,
3128 'yaml' : yaml_parser ,
3229 'yml' : yaml_parser
3330}
3431
3532
36- class Config (object ):
33+ class ConfigValue :
34+
35+ def __getitem__ (self , item ):
36+ return self .__dict__ [item ]
37+
38+ def __iter__ (self ):
39+ return self .__dict__ .keys ().__iter__ ()
40+
41+
42+ class Config :
3743 __instance = None
3844
39- def __new__ (cls , schema : dict = None , config_dir : str = 'config' , file_name : Any = DEFAULT_CONFIG_FILES ):
45+ def __new__ (cls , * args , ** kwargs ):
46+ raise RuntimeError ('A instance of config is not allowed, use Config.get_config() instead' )
47+
48+ @classmethod
49+ def get_config (cls , schema : dict = None , config_dir : str = 'config' , file_name : Any = DEFAULT_CONFIG_FILES ):
4050
4151 if cls .__instance is None or schema is not None :
4252 cls .__create_new_instance (schema , config_dir , file_name )
@@ -78,9 +88,9 @@ def __get_file_path(cls, config_dir, file_name):
7888 @classmethod
7989 def __check_schema (cls , schema ):
8090 if schema is None :
81- raise ConfigInvalidSchemaError ('The schema config can not be None' )
91+ raise ConfigError ('The schema config can not be None' )
8292 if type (schema ) is not dict :
83- raise ConfigInvalidSchemaError ('The first config\' s schema element should be a Map' )
93+ raise ConfigError ('The first config\' s schema element should be a Map' )
8494
8595 @classmethod
8696 def __get_file_buff (cls , path_file : str ):
@@ -95,11 +105,11 @@ def __dict_2_obj(cls, data: Any):
95105 _type = type (data )
96106
97107 if _type is dict :
98- obj = object . __new__ ( cls )
108+ obj = ConfigValue ( )
99109 for key , value in data .items ():
100110 if re .search (ENTITY_NAME_PATTERN , key ) is None :
101111 raise ConfigEntitiesWithWrongNameError (
102- 'The entity keys only may have words, number and underscores' )
112+ f 'The key { key } is invalid. The entity keys only may have words, number and underscores. ' )
103113 setattr (obj , key , cls .__dict_2_obj (value ))
104114 return obj
105115 if _type in (list , set , tuple ):
@@ -124,10 +134,6 @@ class ConfigSchemaModelError(ConfigError):
124134 pass
125135
126136
127- class ConfigInvalidSchemaError (ConfigError ):
128- pass
129-
130-
131137class ConfigFileOpenReadError (ConfigError ):
132138 pass
133139
0 commit comments