You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This will allow the same functionality but also add Validation Support
fromdynaconfimportDynaconf, ValidatorclassConfigRead:
""" Reads configuration data from various sources, validates it, and provides attribute-based access. Supports initialization with data from a URL, dictionary, or another ConfigRead instance. """def__init__(self, data=None, start_key=None, validators=None):
""" Initializes the ConfigRead object. Args: data (str, dict, or ConfigRead, optional): * If a string, it's treated as a URL to a YAML file. * If a dictionary, it's used as the configuration data. * If a ConfigRead instance, its data is used. Defaults to None. start_key (str, optional): If provided, processing starts from this key within the data. Defaults to None. validators (list, optional): List of Validator instances for data validation. Defaults to None. """self.validators=validatorsor []
self.settings=Dynaconf() # Initialize DynaconfifdataisnotNone:
self._load_data(data, start_key)
self._load_and_validate_data()
self._set_attributes(self.settings.to_dict())
def_load_data(self, data, start_key=None):
"""Loads configuration data from various sources."""ifisinstance(data, str):
# Assume it's a URLself.settings.load_file(data)
elifisinstance(data, dict):
self.settings.update(data)
elifisinstance(data, ConfigRead):
self.settings.update(data.settings.to_dict())
else:
raiseValueError("Invalid data type. ""Expected str, dict, or ConfigRead.")
ifstart_key:
self.settings=Dynaconf(data=self.settings.get(start_key))
def_load_and_validate_data(self):
"""Loads configuration data and applies validation."""forvalidatorinself.validators:
self.settings.validators.register(validator)
self.settings.validators.validate()
def_set_attributes(self, data):
"""Recursively sets object attributes from the data."""ifisinstance(data, dict):
forkey, valueindata.items():
ifisinstance(value, (dict, list)):
nested_obj=ConfigRead()
nested_obj._set_attributes(value)
value=nested_objifisinstance(key, int):
key='_'+str(key)
setattr(self, key, value)
defget(self, field_path, default=None):
"""Retrieves a field using a dot-separated path."""returnself.settings.get(field_path, default)
# Example usage:validators= [
Validator('DATABASE_URL', must_exist=True),
Validator('API_KEY', is_type_of=str)
]
config=ConfigRead("my_app", validators=validators)
# Access settings as attributesprint(config.database_url)
print(config.api_key)
The text was updated successfully, but these errors were encountered:
Upgrade the configRead Class to use the Dynaconf Library
This will allow the same functionality but also add Validation Support
The text was updated successfully, but these errors were encountered: