config.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. #============================================================================
  2. # This file is part of Pwman3.
  3. #
  4. # Pwman3 is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License, version 2
  6. # as published by the Free Software Foundation;
  7. #
  8. # Pwman3 is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with Pwman3; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  16. #============================================================================
  17. # Copyright (C) 2012 Oz Nahum <nahumoz@gmail.com>
  18. #============================================================================
  19. # Copyright (C) 2006 Ivan Kelly <ivan@ivankelly.net>
  20. #============================================================================
  21. from ConfigParser import ConfigParser, ParsingError
  22. import copy
  23. class ConfigException(Exception):
  24. """Basic exception for config."""
  25. def __init__(self, message):
  26. self.message = message
  27. def __str__(self):
  28. return "{}: {}".format(self.__class__.__name__,
  29. self.message) # pragma: no cover
  30. class ConfigNoConfigException(ConfigException):
  31. pass
  32. _file = None
  33. _conf = dict()
  34. _defaults = dict()
  35. def set_conf(conf_dict):
  36. global _conf
  37. _conf = conf_dict
  38. def set_defaults(defaults):
  39. global _defaults
  40. _defaults = defaults
  41. def add_defaults(defaults):
  42. global _defaults
  43. for n in defaults.keys():
  44. if n not in _defaults:
  45. _defaults[n] = dict()
  46. for k in defaults[n].keys():
  47. _defaults[n][k] = defaults[n][k]
  48. def get_value(section, name):
  49. global _conf, _defaults
  50. try:
  51. return _conf[section][name]
  52. except KeyError:
  53. pass
  54. try:
  55. value = _defaults[section][name]
  56. set_value(section, name, value)
  57. return value
  58. except KeyError:
  59. pass
  60. return ''
  61. def set_value(section, name, value):
  62. global _conf
  63. if section not in _conf:
  64. _conf[section] = dict()
  65. _conf[section][name] = value
  66. def get_conf():
  67. """
  68. Get a copy of the config.
  69. Modifications have no effect.
  70. This function only serves for allowing applications
  71. to output the config to the user"""
  72. global _conf
  73. return copy.deepcopy(_conf)
  74. def load(filename):
  75. """Load configuration from 'filename'."""
  76. global _conf, _file
  77. _file = filename
  78. parser = ConfigParser()
  79. fp = None
  80. try:
  81. try:
  82. fp = open(filename, "r")
  83. parser.readfp(fp)
  84. except ParsingError as e:
  85. raise ConfigException(e)
  86. except IOError as e:
  87. raise ConfigNoConfigException(e)
  88. finally:
  89. if (fp):
  90. fp.close()
  91. for section in parser.sections():
  92. for option in parser.options(section):
  93. set_value(section, option, parser.get(section, option))
  94. def set_config(config_dict):
  95. global _conf
  96. _conf = config_dict
  97. def save(filename=None):
  98. """Save the configuration to 'filename'."""
  99. global _conf, _file
  100. if not filename:
  101. filename = _file
  102. parser = ConfigParser()
  103. for key in _conf.keys():
  104. if not parser.has_section(key):
  105. parser.add_section(key)
  106. sectiondict = _conf[key]
  107. if isinstance(sectiondict, dict):
  108. for optionkey in sectiondict.keys():
  109. parser.set(key, optionkey, sectiondict[optionkey])
  110. try:
  111. fp = file(filename, "w+")
  112. parser.write(fp)
  113. fp.close()
  114. except IOError as e:
  115. raise ConfigException(str(e))