ems/src/modules/database.py

105 lines
2.5 KiB
Python
Raw Normal View History

'''
Created on 26.11.2013
@author: Philipp Rauch
'''
from MySQLdb import connect
from datetime import date, timedelta
from decimal import Decimal
tables = {}
def get_tables(cur, db):
sql_tables = 'SHOW TABLES FROM %s'
tables = []
cur.execute(sql_tables % db)
#TODO try - except
for i in cur:
tables.append(i[0])
return tables
def get_prime(cur, tabele):
sql_get_prim = "SHOW COLUMNS FROM %s WHERE `Key` = 'PRI'"
sql_get_no_prim = "SHOW COLUMNS FROM %s WHERE `Key` != 'PRI'"
collum = []
cur.execute(sql_get_prim % tabele)
#TODO try - except
for i in cur:
collum.append(i[0])
cur.execute(sql_get_no_prim % tabele)
for i in cur:
collum.append(i[0])
return collum
def setup(conf):
'''
establishes a connection to the database and returns a cursor
@return: cursor to the database
'''
connection = connect(host = conf['mySQL_server'],
user = conf['mySQL_user'],
passwd = conf['mySQL_pass'],
db = conf['mySQL_database'],
port = int(conf['mySQL_port']))
cursor = connection.cursor()
tab = get_tables(cursor, conf['mySQL_database'])
for i in tab:
primes = get_prime(cursor, i)
tables[i] = primes
print tables
return cursor
def loop(cursor, item):
'''
'''
sql_values = 'SELECT * FROM %s ORDER BY %s DESC LIMIT 1'
path = item.split('/')
if path[0] == '':
path.remove('')
table = path[len(path) -1]
if table == 'device':
tmp = { table : {} }
for i in tables.keys():
tmp[table][i] = {}
return tmp
cursor.execute(sql_values % (table, tables[table][0]))
values = []
for row in cursor:
values = row
result = {}
for i in range(0, len(tables[table])):
if values == []:
result[tables[table][i]] = None
else:
if isinstance(values[i], date) or isinstance(values[i], timedelta):
result[tables[table][i]] = str(values[i])
elif isinstance(values[i], Decimal):
result[tables[table][i]] = float(values[i])
else:
result[tables[table][i]] = values[i]
# for p in range(len(path)):
# result = { path.pop() : result }
result = {item : result}
return result
2013-12-13 12:34:24 +01:00
def close(cursor):
pass