]> git.ipfire.org Git - people/shoehn/ipfire.org.git/blob - www/webapp/uriel.py
Initial checkin.
[people/shoehn/ipfire.org.git] / www / webapp / uriel.py
1 #!/usr/bin/python
2
3 import operator
4 import MySQLdb as sql
5
6 allowed_items = [ "cpu_mhz", "cpu_model", "formfactor", "lang", "model",
7 "ram_mb", "storage_mb", "system", "vendor", ]
8
9 class Database(object):
10 _name = "uriel"
11 _table = "hosts"
12
13 def __init__(self):
14 self.connection = sql.connect(user="uriel", db=self._name)
15
16 self._count = None
17
18 def cursor(self):
19 return self.connection.cursor()
20
21 def table(self, item, sort=0, consolidate=0):
22 c = self.cursor()
23 c.execute("SELECT value FROM %s WHERE item = '%s'" % (self._table, item,))
24
25 count = 0
26 results = {}
27 ret = []
28
29 if consolidate:
30 result = c.fetchone()
31 while result:
32 count += 1
33 result = "%s" % result
34
35 if results.has_key(result):
36 results[result] += 1
37 else:
38 results[result] = 1
39
40 result = c.fetchone()
41
42 for i in results.items():
43 ret.append(i)
44
45 if sort:
46 ret = sorted(ret, key=operator.itemgetter(1))
47 ret.reverse()
48
49 else:
50 result = c.fetchone()
51 while result:
52 ret.append(int("%s" % result))
53 result = c.fetchone()
54
55 if sort:
56 ret.sort()
57
58 count = len(ret)
59
60 c.close()
61 return (ret, count)
62
63 def count(self):
64 if not self._count:
65 c = self.cursor()
66 c.execute("SELECT COUNT(DISTINCT(id)) FROM %s" % self._table)
67 self._count = int("%s" % c.fetchone())
68 c.close()
69 return self._count
70
71 def get(self, id, item):
72 c = self.cursor()
73 c.execute("SELECT value FROM %s WHERE id = '%s' AND item = '%s'" % \
74 (self._table, id, item,))
75 ret = c.fetchall() or None
76 c.close()
77 return ret
78
79 def set(self, id, item, value):
80 c = self.cursor()
81 if self.get(id, item):
82 c.execute("UPDATE %s SET value = '%s' WHERE id = '%s' AND item = '%s'" % \
83 (self._table, value, id, item,))
84 else:
85 c.execute("INSERT INTO %s(id, item, value) VALUES('%s', '%s', '%s')" % \
86 (self._table, id, item, value))
87 c.close()