/circuits/app/config.py

https://bitbucket.org/prologic/circuits/ · Python · 91 lines · 52 code · 27 blank · 12 comment · 11 complexity · a2f0fb5969fa2b135ba3debfde114be3 MD5 · raw file

  1. # Module: config
  2. # Date: 13th August 2008
  3. # Author: James Mills, prologic at shortcircuit dot net dot au
  4. """Config
  5. Configuration Component. This component uses the standard
  6. ConfigParser.ConfigParser class and adds support for saving
  7. the configuration to a file.
  8. """
  9. try:
  10. from configparser import ConfigParser
  11. except ImportError:
  12. from ConfigParser import ConfigParser
  13. from circuits import handler, BaseComponent, Event
  14. class ConfigEvent(Event):
  15. """Config Event"""
  16. _target = "config"
  17. class Load(ConfigEvent):
  18. """Load Config Event"""
  19. success = "load_success", ConfigEvent._target
  20. failure = "load_failure", ConfigEvent._target
  21. class Save(ConfigEvent):
  22. """Save Config Event"""
  23. success = "save_success", ConfigEvent._target
  24. failure = "save_failure", ConfigEvent._target
  25. class Config(BaseComponent):
  26. channel = "config"
  27. def __init__(self, filename, defaults=None, channel=channel):
  28. super(Config, self).__init__(channel=channel)
  29. self._config = ConfigParser(defaults=defaults)
  30. self._filename = filename
  31. @handler("load")
  32. def load(self):
  33. self._config.read(self._filename)
  34. @handler("save")
  35. def save(self):
  36. with open(self._filename, "w") as f:
  37. self._config.write(f)
  38. def add_section(self, section):
  39. return self._config.add_section(section)
  40. def get(self, section, option, default=None, raw=False, vars=None):
  41. if self._config.has_option(section, option):
  42. return self._config.get(section, option, raw=raw, vars=vars)
  43. else:
  44. return default
  45. def getint(self, section, option, default=0):
  46. if self._config.has_option(section, option):
  47. return self._config.getint(section, option)
  48. else:
  49. return default
  50. def getfloat(self, section, option, default=0.0):
  51. if self._config.has_option(section, option):
  52. return self._config.getfloat(section, option)
  53. else:
  54. return default
  55. def getboolean(self, section, option, default=False):
  56. if self._config.has_option(section, option):
  57. return self._config.getboolean(section, option)
  58. else:
  59. return default
  60. def has_section(self, section):
  61. return self._config.has_section(section)
  62. def set(self, section, option, value):
  63. return self._config.set(section, option, value)