PageRenderTime 22ms CodeModel.GetById 1ms app.highlight 16ms RepoModel.GetById 1ms app.codeStats 0ms

/circuits/app/config.py

https://bitbucket.org/prologic/circuits/
Python | 91 lines | 52 code | 27 blank | 12 comment | 4 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
 5"""Config
 6
 7Configuration Component. This component uses the  standard
 8ConfigParser.ConfigParser class and adds support for saving
 9the configuration to a file.
10"""
11
12
13try:
14    from configparser import ConfigParser
15except ImportError:
16    from ConfigParser import ConfigParser
17
18from circuits import handler, BaseComponent, Event
19
20
21class ConfigEvent(Event):
22    """Config Event"""
23
24    _target =  "config"
25
26
27class Load(ConfigEvent):
28    """Load Config Event"""
29
30    success = "load_success", ConfigEvent._target
31    failure = "load_failure", ConfigEvent._target
32
33
34class Save(ConfigEvent):
35    """Save Config Event"""
36
37    success = "save_success", ConfigEvent._target
38    failure = "save_failure", ConfigEvent._target
39
40
41class Config(BaseComponent):
42
43    channel = "config"
44
45    def __init__(self, filename, defaults=None, channel=channel):
46        super(Config, self).__init__(channel=channel)
47
48        self._config = ConfigParser(defaults=defaults)
49        self._filename = filename
50
51    @handler("load")
52    def load(self):
53        self._config.read(self._filename)
54
55    @handler("save")
56    def save(self):
57        with open(self._filename, "w") as f:
58            self._config.write(f)
59
60    def add_section(self, section):
61        return self._config.add_section(section)
62
63    def get(self, section, option, default=None, raw=False, vars=None):
64        if self._config.has_option(section, option):
65            return self._config.get(section, option, raw=raw, vars=vars)
66        else:
67            return default
68
69    def getint(self, section, option, default=0):
70        if self._config.has_option(section, option):
71            return self._config.getint(section, option)
72        else:
73            return default
74
75    def getfloat(self, section, option, default=0.0):
76        if self._config.has_option(section, option):
77            return self._config.getfloat(section, option)
78        else:
79            return default
80
81    def getboolean(self, section, option, default=False):
82        if self._config.has_option(section, option):
83            return self._config.getboolean(section, option)
84        else:
85            return default
86
87    def has_section(self, section):
88        return self._config.has_section(section)
89
90    def set(self, section, option, value):
91        return self._config.set(section, option, value)