Geen omschrijving
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

settings_loader.py 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. #-*- coding: utf-8 -*-
  2. import configparser
  3. import os
  4. import glob
  5. import copy
  6. from lodel.settings.utils import *
  7. from lodel.settings.validator import SettingsValidationError
  8. from lodel.settings.utils import SettingsError, SettingsErrors
  9. ##@brief Merges and loads configuration files
  10. class SettingsLoader(object):
  11. ## To avoid the DEFAULT section whose values are found in all sections, we
  12. # have to give it an unsual name
  13. DEFAULT_SECTION = 'lodel2_default_passaway_tip'
  14. ## @brief Virtual filename when default value is used
  15. DEFAULT_FILENAME = 'default_value'
  16. ##@brief Constructor
  17. # @param conf_path str : conf.d path
  18. def __init__(self,conf_path):
  19. self.__conf_path=conf_path
  20. self.__conf_sv=dict()
  21. self.__conf=self.__merge()
  22. # Stores errors
  23. self.__errors_list = []
  24. ##@brief Lists and merges files in settings_loader.conf_path
  25. # @return dict()
  26. def __merge(self):
  27. conf = dict()
  28. l_dir = glob.glob(self.__conf_path+'/*.ini')
  29. for f_ini in l_dir:
  30. config = configparser.ConfigParser(default_section = self.DEFAULT_SECTION ,interpolation=None)
  31. config.read(f_ini)
  32. for section in [ s for s in config if s != self.DEFAULT_SECTION ]:
  33. if section not in conf:
  34. conf[section] = dict()
  35. for param in config[section]:
  36. if param not in conf[section]:
  37. conf[section][param]=dict()
  38. conf[section][param]['value'] = config[section][param]
  39. conf[section][param]['file'] = f_ini
  40. self.__conf_sv[section + ':' + param]=f_ini
  41. else:
  42. raise SettingsError("Error redeclaration of key %s in section %s. Found in %s and %s" % (
  43. section,
  44. param,
  45. f_ini,
  46. conf[section][param]['file']))
  47. return conf
  48. ##@brief Returns option if exists default_value else and validates
  49. # @param section str : name of the section
  50. # @param keyname str
  51. # @param validator callable : takes one argument value and raises validation fail
  52. # @param default_value *
  53. # @param mandatory bool
  54. # @return the option
  55. def getoption(self,section,keyname,validator,default_value=None,mandatory=False):
  56. conf=self.__conf
  57. if section in conf:
  58. sec=conf[section]
  59. if keyname in sec:
  60. optionstr=sec[keyname]['value']
  61. try:
  62. option= validator(sec[keyname]['value'])
  63. except Exception as e:
  64. # Generating nice exceptions
  65. if sec[keyname]['file'] == SettingsLoader.DEFAULT_FILENAME:
  66. expt = SettingsError( msg = 'Mandatory settings not found',
  67. key_id = section+'.'+keyname)
  68. self.__errors_list.append(expt)
  69. else:
  70. expt = SettingsValidationError(
  71. "For %s.%s : %s" %
  72. (section, keyname,e)
  73. )
  74. expt2 = SettingsError( msg = str(expt),
  75. key_id = section+'.'+keyname,
  76. filename = sec[keyname]['file'])
  77. self.__errors_list.append(expt2)
  78. return
  79. try:
  80. del self.__conf_sv[section + ':' + keyname]
  81. except KeyError: #allready fetched
  82. pass
  83. return option
  84. elif default_value is None and mandatory:
  85. msg = "Default value mandatory for option %s" % keyname
  86. expt = SettingsError( msg = msg,
  87. key_id = section+'.'+keyname,
  88. filename = sec[keyname]['file'])
  89. self.__errors_list.append(expt)
  90. return
  91. sec[keyname]=dict()
  92. sec[keyname]['value'] = default_value
  93. sec[keyname]['file'] = SettingsLoader.DEFAULT_FILENAME
  94. return default_value
  95. else:
  96. conf[section]=dict()
  97. conf[section][keyname]=dict()
  98. conf[section][keyname]['value'] = default_value
  99. conf[section][keyname]['file'] = SettingsLoader.DEFAULT_FILENAME
  100. return default_value
  101. ##@brief Sets option in a config section. Writes in the conf file
  102. # @param section str : name of the section
  103. # @param keyname str
  104. # @param value str
  105. # @param validator callable : takes one argument value and raises validation fail
  106. # @return the option
  107. def setoption(self,section,keyname,value,validator):
  108. f_conf=copy.copy(self.__conf[section][keyname]['file'])
  109. if f_conf == SettingsLoader.DEFAULT_FILENAME:
  110. f_conf = self.__conf_path + '/generated.ini'
  111. conf=self.__conf
  112. conf[section][keyname] = value
  113. config = configparser.ConfigParser()
  114. config.read(f_conf)
  115. if section not in config:
  116. config[section]={}
  117. config[section][keyname] = validator(value)
  118. with open(f_conf, 'w') as configfile:
  119. config.write(configfile)
  120. ##@brief Saves new partial configuration. Writes in the conf files corresponding
  121. # @param sections dict
  122. # @param validators dict of callable : takes one argument value and raises validation fail
  123. def saveconf(self, sections, validators):
  124. for sec in sections:
  125. for kname in sections[sec]:
  126. self.setoption(sec,kname,sections[sec][kname],validators[sec][kname])
  127. ##@brief Returns the section to be configured
  128. # @param section_prefix str
  129. # @param default_section str
  130. # @return the section as dict()
  131. def getsection(self,section_prefix,default_section=None):
  132. conf=copy.copy(self.__conf)
  133. sections=[]
  134. if section_prefix in conf:
  135. sections.append(section_prefix)
  136. for sect_names in conf:
  137. if sect_names in sections:
  138. pass
  139. elif sect_names.startswith(section_prefix + '.'):
  140. sections.append(sect_names)
  141. if sections == [] and default_section:
  142. sections.append(section_prefix + '.' + default_section)
  143. elif sections == []:
  144. raise NameError("Not existing settings section : %s" % section__prefix)
  145. return sections;
  146. ##@brief Returns invalid settings
  147. #
  148. # This method returns all the settings that was not fecthed by
  149. # getsection() method. For the Settings object it allows to know
  150. # the list of invalids settings keys
  151. # @return a dict with SECTION_NAME+":"+KEY_NAME as key and the filename
  152. # where the settings was found as value
  153. def getremains(self):
  154. return self.__conf_sv
  155. ##@brief Raise a SettingsErrors exception if some confs remains
  156. #@note typically used at the end of Settings bootstrap
  157. def raise_errors(self):
  158. remains = self.getremains()
  159. err_l = self.__errors_list
  160. for key_id, filename in remains.items():
  161. err_l.append(SettingsError( msg = "Invalid configuration key",
  162. key_id = key_id,
  163. filename = filename))
  164. if len(err_l) > 0:
  165. raise SettingsErrors(err_l)
  166. else:
  167. return