3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
17 from yarf.exceptions import ConfigError
20 class INILoader(dict):
21 def __init__(self, inifile, defaults=None, defaultsection=None):
22 super(INILoader, self).__init__(self)
23 self.inifile = inifile
24 self.handlers = 'handlers'
25 self.configparser = configparser.ConfigParser(defaults)
26 self.config = self.configparser.read(inifile)
27 self.defaultsection = defaultsection
28 if inifile not in self.config:
29 raise ConfigError("Failed to read config file: %s" % inifile)
31 def get_sections(self):
32 return self.configparser.sections()
34 def get_handlers(self, section):
35 return self[section][self.handlers].split(',')
37 def __getitem__(self, key):
39 return self.configparser[key]
41 raise ConfigError("No such key %s" % key)
43 def get(self, key, section=None, type_of_value=str):
44 if section is None and self.defaultsection is not None:
45 section = self.defaultsection
49 if type_of_value is int:
50 return self.configparser.getint(section, key)
51 elif type_of_value is bool:
52 return self.configparser.getboolean(section, key)
53 elif type_of_value is float:
54 return self.configparser.getfloat(section, key)
55 return self.configparser.get(section, key)
58 return self.configparser.sections()
60 def get_section(self, section, format='list'):
61 if section in self.keys():
62 items = self.configparser.items(section)