No Description
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 5.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. #-*- coding: utf-8 -*-
  2. import configparser
  3. import os
  4. import glob
  5. import copy
  6. from lodel.settings.utils import *
  7. ##@brief Merges and loads configuration files
  8. class SettingsLoader(object):
  9. ## To avoid the DEFAULT section whose values are found in all sections, we
  10. # have to give it an unsual name
  11. DEFAULT_SECTION = 'lodel2_default_passaway_tip'
  12. ##@brief Constructor
  13. # @param conf_path str : conf.d path
  14. def __init__(self,conf_path):
  15. self.__conf_path=conf_path
  16. self.__conf_sv=dict()
  17. self.__conf=self.__merge()
  18. ##@brief Lists and merges files in settings_loader.conf_path
  19. # @return dict()
  20. def __merge(self):
  21. conf = dict()
  22. l_dir = glob.glob(self.__conf_path+'/*.ini')
  23. for f_ini in l_dir:
  24. config = configparser.ConfigParser(default_section = self.DEFAULT_SECTION ,interpolation=None)
  25. config.read(f_ini)
  26. for section in [ s for s in config if s != self.DEFAULT_SECTION ]:
  27. if section not in conf:
  28. conf[section] = dict()
  29. for param in config[section]:
  30. if param not in conf[section]:
  31. conf[section][param]=dict()
  32. conf[section][param]['value'] = config[section][param]
  33. conf[section][param]['file'] = f_ini
  34. self.__conf_sv[section + ':' + param]=f_ini
  35. else:
  36. raise SettingsError("Error redeclaration of key %s in section %s. Found in %s and %s" % (
  37. section,
  38. param,
  39. f_ini,
  40. conf[section][param]['file']))
  41. return conf
  42. ##@brief Returns option if exists default_value else and validates
  43. # @param section str : name of the section
  44. # @param keyname str
  45. # @param validator callable : takes one argument value and raises validation fail
  46. # @param default_value *
  47. # @param mandatory bool
  48. # @return the option
  49. def getoption(self,section,keyname,validator,default_value=None,mandatory=False):
  50. conf=self.__conf
  51. if section in conf:
  52. sec=conf[section]
  53. if keyname in sec:
  54. optionstr=sec[keyname]['value']
  55. option= validator(sec[keyname]['value'])
  56. try:
  57. del self.__conf_sv[section + ':' + keyname]
  58. except KeyError: #allready fetched
  59. pass
  60. return option
  61. elif default_value is None and mandatory:
  62. raise SettingsError("Default value mandatory for option %s" % keyname)
  63. sec[keyname]=dict()
  64. sec[keyname]['value'] = default_value
  65. sec[keyname]['file'] = 'default_value'
  66. return default_value
  67. else:
  68. conf[section]=dict()
  69. conf[section][keyname]=dict()
  70. conf[section][keyname]['value'] = default_value
  71. conf[section][keyname]['file'] = 'default_value'
  72. return default_value
  73. ##@brief Sets option in a config section. Writes in the conf file
  74. # @param section str : name of the section
  75. # @param keyname str
  76. # @param value str
  77. # @param validator callable : takes one argument value and raises validation fail
  78. # @return the option
  79. def setoption(self,section,keyname,value,validator):
  80. f_conf=copy.copy(self.__conf[section][keyname]['file'])
  81. if f_conf == 'default_value':
  82. f_conf = self.__conf_path + '/generated.ini'
  83. conf=self.__conf
  84. conf[section][keyname] = value
  85. config = configparser.ConfigParser()
  86. config.read(f_conf)
  87. if section not in config:
  88. config[section]={}
  89. config[section][keyname] = validator(value)
  90. with open(f_conf, 'w') as configfile:
  91. config.write(configfile)
  92. ##@brief Saves new partial configuration. Writes in the conf files corresponding
  93. # @param sections dict
  94. # @param validators dict of callable : takes one argument value and raises validation fail
  95. def saveconf(self, sections, validators):
  96. for sec in sections:
  97. for kname in sections[sec]:
  98. self.setoption(sec,kname,sections[sec][kname],validators[sec][kname])
  99. ##@brief Returns the section to be configured
  100. # @param section_prefix str
  101. # @param default_section str
  102. # @return the section as dict()
  103. def getsection(self,section_prefix,default_section=None):
  104. conf=copy.copy(self.__conf)
  105. sections=[]
  106. if section_prefix in conf:
  107. sections.append(section_prefix)
  108. for sect_names in conf:
  109. if sect_names in sections:
  110. pass
  111. elif sect_names.startswith(section_prefix + '.'):
  112. sections.append(sect_names)
  113. if sections == [] and default_section:
  114. sections.append(section_prefix + '.' + default_section)
  115. elif sections == []:
  116. raise NameError("Not existing settings section : %s" % section__prefix)
  117. return sections;
  118. ## @brief Returns invalid settings
  119. #
  120. # This method returns all the settings that was not fecthed by
  121. # getsection() method. For the Settings object it allows to know
  122. # the list of invalids settings keys
  123. # @return a dict with SECTION_NAME+":"+KEY_NAME as key and the filename
  124. # where the settings was found as value
  125. def getremains(self):
  126. return self.__conf_sv