olivia_finder.utilities.config

 1import configparser
 2import os
 3from typing import Optional
 4from .singleton_decorator import singleton
 5from .exception import ConfigFileNotFound, ConfigKeyNotFound
 6
 7
 8@singleton
 9class Configuration:
10    """
11    Utility class for obtaining configurations from a config.ini file.
12    The config.ini file is read only once and the values are stored in a dictionary.
13    The config.ini file path can be changed by passing the path to the constructor.
14
15    .. warning:: It is necessary to initialize the configuration, the most comfortable and global way to do so is through an environment variable
16
17    Attributes
18    ----------
19    _config : dict
20        Configurations read from the config file
21    """
22
23    # Class variables
24    # ---------------
25    _config = {}
26    
27    def __init__(self, file_path: Optional[str] = None):
28        '''
29        Initialize the class, read the config file and store the values in a dictionary
30
31        Parameters
32        ----------
33        file_path : str, optional
34            Path to the config file, by default None, 
35            in which case the path is read from the environment variable OLIVIA_FINDER_CONFIG_FILE_PATH
36
37        Raises
38        ------
39        ConfigFileNotFoundError
40            If the config file is not found
41        '''
42
43        if file_path is None:
44            # Read the config file from environment variable
45            file_path = os.environ.get('OLIVIA_FINDER_CONFIG_FILE_PATH')
46
47        # Load data from ini file
48        config_parser = configparser.ConfigParser()
49
50        try:
51            # Read the config file
52            with open(f'{file_path}', encoding='utf-8') as f:
53                config_parser.read_file(f)
54
55        # If the file is not found, raise an exception
56        except FileNotFoundError as e:
57            raise ConfigFileNotFound(f'Config file not found in {file_path}') from e
58        
59        self._config = dict(config_parser)
60
61    def get_key(self, section:str, key: str):
62        '''
63        Get a value from the config file by section and key
64
65        Parameters
66        ----------
67        section : str
68            Section of the config file
69        key : str
70            Key of the config file
71
72        Returns
73        -------
74        str
75            Value of the key in the section
76        
77        Raises
78        ------
79        ConfigKeyNotFoundError
80            If the key is not found in the config file
81
82        '''
83
84        try:
85            value = self._config[section][key]
86        except KeyError as e:
87            raise ConfigKeyNotFound(f'Key {key} not found in section {section}') from e
88        
89        return value