#!/usr/bin/python # -*- coding: utf-8 -*- import json import logging log = logging.getLogger(__name__) import MySQLdb class DB(object): def __init__(self,host,user,pwd,db): self.host = host self.user = user self.pwd = pwd self.db = db self.con = 0 def connect(self): if self.con == 0: try: con = MySQLdb.connect(self.host,self.user,self.pwd,self.db) self.con = con return True except Exception, e: log.fatal('Error connecting to database : %s' % e) return def do_sql(self,sql): try: c=self.con.cursor() c.execute(sql) self.con.commit() return c except Exception,e: log.error('Error executing request %s : %s' % (sql,e)) return False def select(self,sql): ret=self.do_sql(sql) if ret!=False: return ret.fetchall() return ret def login(self,email,password): ret=self.select("SELECT email,name,password FROM users WHERE email='%s' AND password='%s'" % (email,password)) log.debug(ret) if ret: if len(ret)==1: return { 'email': ret[0][0], 'name': ret[0][1] } elif len(ret)>=1: log.warning('Duplicate user %s in database' % email) elif ret==(): return { 'loginerror': 'Utilisateur inconnu' } return { 'loginerror': 'Erreur inconnu' } def subscribe(self,email,name,password): ret=self.select("SELECT count(*) as count FROM users WHERE email='%s'" % (email)) log.debug(ret) if ret[0][0]!=0: return {'subscribeerror': u'Cette adresse mail est déjà associés a un compte !'} else: if self.do_sql("INSERT INTO users (email,name,password) VALUES ('%s','%s','%s')" % (email,name,password)): return { 'email': email, 'name': name, 'password': password } return {'subscribeerror': u'Une erreur est survenue durant votre inscription :('} def sync_group(self,email,groups): db_groups=self.get_group(email) json_group=json.dumps(groups) if db_groups!=False: if db_groups=={}: if groups=={}: return {'groups': {}} else: if self.do_sql("INSERT INTO groups (email,groups) VALUES ('%s','%s')" % (email,json_group)): return {'groups': groups} elif groups=={}: return {'groups': db_groups} else: if self.do_sql("UPDATE groups SET groups='%s' WHERE email='%s'" % (json_group,email)): return {'groups': groups} return {'syncerror': 'Erreur inconnu'} def get_group(self,email): ret=self.select("SELECT groups FROM groups WHERE email='%s'" % email) if ret!=False: if len(ret)==1: return json.loads(ret[0][0]) else: return {} else: return False