1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 """
18 ==================
19 DB access module
20 ==================
21
22 DB access module.
23 """
24 __author__ = u"Andr\xe9 Malo"
25 __docformat__ = "restructuredtext en"
26
27 import ConfigParser as _config_parser
28 import os as _os
29
30 from wtf.ext.db._exceptions import DBConfigurationError
31 from wtf import util as _wtf_util
32
33
34
35
36
37 DEFAULT_CONF = '/etc/wtf/ext/db.conf'
38
39
41 """
42 Load config
43
44 :Parameters:
45 `dbconf` : ``str``
46 DB config filename
47
48 :Return: Config dict
49 :Rtype: ``dict``
50 """
51 parser = _config_parser.RawConfigParser()
52 try:
53 fp = open(dbconf, 'rb')
54 try:
55 parser.readfp(fp)
56 finally:
57 fp.close()
58 except IOError, e:
59 raise DBConfigurationError(str(e))
60
61 config = dict((section, dict((opt, parser.get(section, opt))
62 for opt in parser.options(section)
63 )) for section in parser.sections())
64
65 for _, opts in config.items():
66 if 'alias' in opts:
67 alias = opts['alias']
68 opts.clear()
69 opts.update(config[alias])
70
71 return config
72
73
99
100 dbconf = resolve(dbconf, 'WTF_EXT_DB_CONF', DEFAULT_CONF)
101 config = load_from_file(dbconf)
102
103 def driver(dbname):
104 """
105 Determine driver module
106
107 :Parameters:
108 `dbname` : ``str``
109 DB name (section token in db.conf)
110
111 :Return: Driver module
112 :Rtype: ``module``
113
114 :Exceptions:
115 - `DBConfigurationError` : DB not configured
116 - `KeyError` : DB name not found
117 - `ImportError` : Driver not found
118 """
119 return _wtf_util.load_dotted(
120 'wtf.ext.db._driver_%s' % config[dbname]['driver']
121 )
122
123 def connect(dbname, **kwargs):
124 """
125 Connect to database
126
127 :Parameters:
128 `dbname` : ``str``
129 DB name (section token in db.conf)
130
131 `kwargs` : ``dict``
132 Additional parameters for adapter connect() call
133
134 :Return: new connection
135 :Rtype: connection object (DBAPI 2)
136
137 :Exceptions:
138 - `DBConfigurationError` : DB not configured
139 - `KeyError` : DB name not found
140 - `ImportError` : Driver not found
141 """
142 conf = config[dbname].copy()
143 db_driver = driver(dbname)
144 conf.pop('driver', None)
145 if 'passwd' in conf and unpack_password is not None:
146 passwd = conf['passwd']
147 conf['passwd'] = lambda: unpack_password(passwd)
148 return db_driver.connect(conf, kwargs)
149 connect.config = config
150
151 return driver, connect
152