Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

upgrade ConfigRead to support DynaConf Library #22

Open
Ulrond opened this issue Oct 31, 2024 · 0 comments
Open

upgrade ConfigRead to support DynaConf Library #22

Ulrond opened this issue Oct 31, 2024 · 0 comments
Labels
enhancement New feature or request

Comments

@Ulrond
Copy link
Contributor

Ulrond commented Oct 31, 2024

Upgrade the configRead Class to use the Dynaconf Library

This will allow the same functionality but also add Validation Support

from dynaconf import Dynaconf, Validator

class ConfigRead:
    """
    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 = validators or []
        self.settings = Dynaconf()  # Initialize Dynaconf

        if data is not None:
            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."""
        if isinstance(data, str):
            # Assume it's a URL
            self.settings.load_file(data)
        elif isinstance(data, dict):
            self.settings.update(data)
        elif isinstance(data, ConfigRead):
            self.settings.update(data.settings.to_dict())
        else:
            raise ValueError("Invalid data type. "
                             "Expected str, dict, or ConfigRead.")

        if start_key:
            self.settings = Dynaconf(data=self.settings.get(start_key))

    def _load_and_validate_data(self):
        """Loads configuration data and applies validation."""
        for validator in self.validators:
            self.settings.validators.register(validator)
        self.settings.validators.validate()

    def _set_attributes(self, data):
        """Recursively sets object attributes from the data."""
        if isinstance(data, dict):
            for key, value in data.items():
                if isinstance(value, (dict, list)):
                    nested_obj = ConfigRead()
                    nested_obj._set_attributes(value)
                    value = nested_obj
                if isinstance(key, int):
                    key = '_' + str(key)
                setattr(self, key, value)

    def get(self, field_path, default=None):
        """Retrieves a field using a dot-separated path."""
        return self.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 attributes
print(config.database_url)  
print(config.api_key)
@Ulrond Ulrond added the enhancement New feature or request label Oct 31, 2024
@Ulrond Ulrond moved this to Todo in UT-Core Roadmap Nov 13, 2024
@Ulrond Ulrond added this to the ut-raft: 1.2.0: New features milestone Nov 18, 2024
@TB-1993 TB-1993 removed this from the ut-raft: 1.2.0: New features milestone Nov 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
Status: Todo
Development

No branches or pull requests

2 participants