-
Notifications
You must be signed in to change notification settings - Fork 0
/
data.py
44 lines (33 loc) · 1.07 KB
/
data.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import postgresql
import cherrypy
from cherrypy.process import wspbus, plugins
class DatabasePlugin(plugins.SimplePlugin):
def __init__(self, bus):
plugins.SimplePlugin.__init__(self, bus)
self.db = None
def start(self):
self.bus.log('Starting up DB access')
self.bus.subscribe("get_data", self.get_data)
def stop(self):
self.bus.log('Stopping down DB access')
if self.db:
self.db.close()
self.bus.unsubscribe("get_data", self.get_data)
def reconnect(self):
self.bus.log('Reconnect..')
self.db = None
conn = cherrypy.config['db_str']
try:
self.db = postgresql.open(conn)
except Exception as e:
self.bus.log('Connection error:', e)
def get_data(self, sql):
if not self.db:
self.reconnect()
self.bus.log('get_data: ' + sql)
try:
res = self.db.prepare(sql)
except Exception as e:
res = None
self.reconnect()
return res