]> andersk Git - sql.git/blame - lib/python/mitsql/config.py
implemented base interface
[sql.git] / lib / python / mitsql / config.py
CommitLineData
e4fd5e1b
JP
1"""
2Global configuration objects.
3
4Joe Presbrey <presbrey@mit.edu>
5"""
6
7from ConfigParser import ConfigParser, NoSectionError, NoOptionError
8import os
9
10_ENV_BASE='_SQL_MIT_EDU'
11
12class Section(object):
13 """Configuration section namespace."""
14 def __init__(self, d):
15 self.items = d
16
17 def __getattr__(self, k):
18 v = self.items.get(k, None)
19 try:
20 if str(int(v)) == str(v): v = int(v)
21 except TypeError: pass
22 except ValueError: pass
23 try:
24 if str(v).lower() == 'true': v = True
25 if str(v).lower() == 'false': v = False
26 except TypeError: pass
27 except ValueError: pass
28 return v
29
30 def __iter__(self):
31 return iter(self.items)
32
33 def __str__(self):
34 return str(self.items)
35
36class Config(object):
37 """Base configuration namespace."""
38 def __init__(self, filename, *args, **kwargs):
39 self._cp = ConfigParser(*args, **kwargs)
40 self.read(filename)
41 self._none = Section({})
42
43 def _samefile(self, f1, f2):
44 try:
45 return os.path.samefile(f1, f2)
46 except OSError, e:
47 return False
48
49 def read(self, filename):
50 config_path = [os.path.join(x, filename) for x in [
51 os.path.dirname(__file__),
52 '/etc']]
53 if _ENV_BASE in os.environ:
54 config_path.insert(1, os.path.join(os.environ[_ENV_BASE], 'etc', filename))
55 def append(path):
56 r = os.path.join(path, filename)
57 if not r in config_path:
58 config_path.append(r)
59 if 'HOME' in os.environ:
60 append(os.environ['HOME'])
61 if 'PWD' in os.environ:
62 append(os.environ['PWD'])
63 self._cp.read(config_path)
64 self._sections = dict(map(lambda x: (x, Section(dict(self._cp.items(x)))),
65 self._cp.sections()))
66
67 def get(self, *av, **kw):
68 try: return self._cp.get(*av, **kw)
69 except NoSectionError: return None
70 except NoOptionError: return None
71
72 def __getattr__(self, k):
73 return self._sections.get(k, self._none)
74
75 def __str__(self):
76 d = {}
77 for x in self._cp.sections():
78 d[x] = dict(self._cp.items(x))
79 return str(d)
80
81if __name__ == '__main__':
82 import mitsql
83 print mitsql.config
This page took 0.055628 seconds and 5 git commands to generate.