[58] | 1 |
|
---|
| 2 | import os
|
---|
| 3 | from ConfigParser import SafeConfigParser
|
---|
| 4 |
|
---|
| 5 |
|
---|
| 6 | class Config(object):
|
---|
| 7 | def __init__(self, path=None):
|
---|
| 8 | self.path = path
|
---|
| 9 | self.default_paths = [
|
---|
| 10 | os.path.expanduser('~/'),
|
---|
| 11 | os.path.join(os.path.dirname(__file__),'../etc')
|
---|
| 12 | ]
|
---|
| 13 | self.config = {}
|
---|
| 14 |
|
---|
| 15 | @property
|
---|
| 16 | def filename(self):
|
---|
| 17 | return 'stamper.conf'
|
---|
| 18 |
|
---|
| 19 | @property
|
---|
| 20 | def sections(self):
|
---|
| 21 | return['stamps', 'sum', 'charts', 'collector']
|
---|
| 22 |
|
---|
| 23 | def look_for_config(self):
|
---|
| 24 | """
|
---|
| 25 | Look for the configuration file, following the path names listed in
|
---|
| 26 | the default paths
|
---|
| 27 | """
|
---|
| 28 | for path in self.default_paths:
|
---|
| 29 | full_path = os.path.join(path, self.filename)
|
---|
| 30 | if os.path.isfile(full_path):
|
---|
| 31 | self.path = full_path
|
---|
| 32 | return full_path
|
---|
| 33 | # if we reach here, self.path will be still None, no valid
|
---|
| 34 | # config files were found, and so we raise an exception
|
---|
| 35 | raise IOError('ERROR - Can not find ' + self.filename + \
|
---|
| 36 | ' in your environment')
|
---|
| 37 |
|
---|
| 38 | def load(self):
|
---|
| 39 | if not self.path:
|
---|
| 40 | full_path = self.look_for_config()
|
---|
| 41 | parser = SafeConfigParser()
|
---|
| 42 | parser.read(full_path)
|
---|
| 43 | for section in self.sections:
|
---|
| 44 | self.config[section] = {}
|
---|
| 45 | for name, value in parser.items(section):
|
---|
| 46 | self.config[section][name] = value
|
---|
| 47 | return self.config
|
---|
| 48 |
|
---|
| 49 | def get(self, section, parameter=None):
|
---|
| 50 | if section not in self.config.keys():
|
---|
| 51 | # perhaps the config hasn't been loaded yet
|
---|
| 52 | self.load()
|
---|
| 53 |
|
---|
| 54 | if section not in self.sections:
|
---|
| 55 | raise IndexError('ERROR - ' + section + \
|
---|
| 56 | ' is not one of the available sections: ' + \
|
---|
| 57 | ', '.join(self.sections))
|
---|
| 58 |
|
---|
| 59 | if parameter:
|
---|
| 60 | return self.config[section][parameter]
|
---|
| 61 |
|
---|
| 62 | return self.config[section]
|
---|