]>
Commit | Line | Data |
---|---|---|
940227cb MT |
1 | #!/usr/bin/python |
2 | ||
3 | import logging | |
4 | import tornado.database | |
5 | ||
6 | from misc import Singleton | |
7 | ||
8 | class Row(tornado.database.Row): | |
9 | pass | |
10 | ||
60024cc8 | 11 | MYSQL_SERVER = "mysql-master.ipfire.org" |
940227cb MT |
12 | |
13 | class Databases(object): | |
14 | __metaclass__ = Singleton | |
15 | ||
16 | def __init__(self): | |
17 | self._connections = {} | |
18 | ||
19 | @property | |
20 | def webapp(self): | |
21 | if not self._connections.has_key("webapp"): | |
22 | self._connections["webapp"] = \ | |
23 | Connection(MYSQL_SERVER, "webapp", user="webapp") | |
24 | ||
25 | return self._connections["webapp"] | |
26 | ||
27 | @property | |
28 | def geoip(self): | |
29 | if not self._connections.has_key("geoip"): | |
30 | self._connections["geoip"] = \ | |
31 | Connection(MYSQL_SERVER, "geoip", user="webapp") | |
32 | ||
33 | return self._connections["geoip"] | |
34 | ||
940227cb MT |
35 | |
36 | class Connection(tornado.database.Connection): | |
37 | def __init__(self, *args, **kwargs): | |
38 | logging.debug("Creating new database connection: %s" % args[1]) | |
39 | ||
40 | tornado.database.Connection.__init__(self, *args, **kwargs) | |
41 | ||
42 | def update(self, table, item_id, **items): | |
43 | query = "UPDATE %s SET " % table | |
44 | ||
45 | keys = [] | |
46 | for k, v in items.items(): | |
47 | # Never update id | |
48 | if k == "id": | |
49 | continue | |
50 | ||
51 | keys.append("%s='%s'" % (k, v)) | |
52 | ||
53 | query += ", ".join(keys) | |
54 | query += " WHERE id=%s" % item_id | |
55 | ||
56 | return self.execute(query) | |
57 | ||
58 | def insert(self, table, **items): | |
59 | query = "INSERT INTO %s" % table | |
60 | ||
61 | keys = [] | |
62 | vals = [] | |
63 | ||
64 | for k, v in items.items(): | |
65 | # Never insert id | |
66 | if k == "id": | |
67 | continue | |
68 | ||
69 | keys.append(k) | |
70 | vals.append("'%s'" % v) | |
71 | ||
72 | query += "(%s)"% ", ".join(keys) | |
73 | query += " VALUES(%s)" % ", ".join(vals) | |
74 | ||
75 | return self.execute(query) | |
76 | ||
77 | def _execute(self, cursor, query, parameters): | |
78 | logging.debug("Executing query: %s" % (query % parameters)) | |
79 | ||
80 | return tornado.database.Connection._execute(self, cursor, query, parameters) |