Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/store.py
diff options
context:
space:
mode:
authorflavio <fdanesse@gmail.com>2012-04-26 22:00:54 (GMT)
committer flavio <fdanesse@gmail.com>2012-04-26 22:00:54 (GMT)
commitc388594908413dc39b532da1dadb13f7df1c8e48 (patch)
tree72dae4ecf3fba07a689916c1331a0fa64f3d5fc9 /store.py
parent6639fe3fd851bfb9704c79054799d490013141f8 (diff)
Filtrando
Diffstat (limited to 'store.py')
-rw-r--r--store.py78
1 files changed, 43 insertions, 35 deletions
diff --git a/store.py b/store.py
index 9940403..fdfc131 100644
--- a/store.py
+++ b/store.py
@@ -15,27 +15,35 @@ import shelve
# for future releases
#from xml.dom import minidom
+init_db = """
+CREATE TABLE IF NOT EXISTS notifications (id INTEGER PRIMARY KEY,
+title VARCHAR(30) NOT NULL ON CONFLICT REPLACE DEFAULT '',
+text TEXT NOT NULL ON CONFLICT REPLACE DEFAULT '',
+priority INTEGER NOT NULL,
+launched DATE NOT NULL ON CONFLICT REPLACE DEFAULT 00000000,
+expires DATETIME,
+type VARCHAR(15) NOT NULL ON CONFLICT REPLACE DEFAULT '',
+fav INTEGER NOT NULL ON CONFLICT REPLACE DEFAULT 0 ); """
+
class Db:
def __init__(self, db_filename=None):
- init_db = """
-CREATE TABLE IF NOT EXISTS notifications (id INTEGER PRIMARY KEY,title VARCHAR(30) NOT NULL ON CONFLICT REPLACE DEFAULT '',text TEXT NOT NULL ON CONFLICT REPLACE DEFAULT '', priority INTEGER NOT NULL, launched DATE NOT NULL ON CONFLICT REPLACE DEFAULT 00000000,expires DATETIME, type VARCHAR(15) NOT NULL ON CONFLICT REPLACE DEFAULT '',fav INTEGER NOT NULL ON CONFLICT REPLACE DEFAULT 0 ); """
if db_filename:
self._db_filename = db_filename
else:
- self._db_filename = os.path.join(env.get_data_root(),"messages.db")
+ self._db_filename = os.path.join(env.get_data_root(), "messages.db")
conn = self._connect()
c = conn.cursor()
c.executescript(init_db)
self._close_connection(conn)
- def dict_factory(self,cursor, row):
+ def dict_factory(self, cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
def _connect(self):
- conn = sqlite3.connect(self._db_filename,isolation_level=None)
+ conn = sqlite3.connect(self._db_filename, isolation_level=None)
conn.text_factory = str
return conn
@@ -48,9 +56,9 @@ CREATE TABLE IF NOT EXISTS notifications (id INTEGER PRIMARY KEY,title VARCHAR(3
c = con.cursor()
c.execute('BEGIN TRANSACTION')
try:
- c.execute('insert into notifications(%s,%s,%s,%s,%s,%s,%s,%s) values (?,?,?,?,?,?,?,?)' %tuple(keys), values)
- except sqlite3.IntegrityError,e:
- print "Error al insertar datos: %s" %str(e)
+ c.execute('insert into notifications(%s,%s,%s,%s,%s,%s,%s,%s) values (?,?,?,?,?,?,?,?)' % tuple(keys), values)
+ except sqlite3.IntegrityError, e:
+ print "Error al insertar datos: %s" % str(e)
c.execute('END TRANSACTION')
self._close_connection(con)
@@ -60,9 +68,9 @@ CREATE TABLE IF NOT EXISTS notifications (id INTEGER PRIMARY KEY,title VARCHAR(3
c = con.cursor()
c.execute('BEGIN TRANSACTION')
try:
- c.execute('delete from notifications where id=%i' %id_msg)
- except sqlite3.IntegrityError,e:
- print "Error al eliminar datos: %s" %str(e)
+ c.execute('delete from notifications where id=%i' % id_msg)
+ except sqlite3.IntegrityError, e:
+ print "Error al eliminar datos: %s" % str(e)
c.execute('END TRANSACTION')
self._close_connection(con)
@@ -73,7 +81,7 @@ CREATE TABLE IF NOT EXISTS notifications (id INTEGER PRIMARY KEY,title VARCHAR(3
order = "DESC"
query = "select distinct type from notifications order by type "+order
return map(lambda x:x['type'],self.run_query(query))
-
+
def set_fav(self, id_msg, fav=True):
"""Marca un mensaje como favorito.
Si fav == False lo desmarca"""
@@ -81,15 +89,15 @@ CREATE TABLE IF NOT EXISTS notifications (id INTEGER PRIMARY KEY,title VARCHAR(3
c = con.cursor()
c.execute('BEGIN TRANSACTION')
try:
- c.execute('update notifications set fav=%i where id=%i' %(int(fav),id_msg))
- except sqlite3.IntegrityError,e:
- print "Error al eliminar datos: %s" %str(e)
+ c.execute('update notifications set fav=%i where id=%i' % (int(fav), id_msg))
+ except sqlite3.IntegrityError, e:
+ print "Error al eliminar datos: %s" % str(e)
c.execute('END TRANSACTION')
self._close_connection(con)
def is_fav(self, id_msg):
- fav = self.run_query("select fav from notifications where id=%i" %id_msg)
- return fav[0]['fav']
+ fav = self.run_query("select fav from notifications where id=%i" % id_msg)
+ return bool(int(fav[0]['fav']))
def run_query(self, query):
"""
@@ -113,12 +121,12 @@ CREATE TABLE IF NOT EXISTS notifications (id INTEGER PRIMARY KEY,title VARCHAR(3
if args:
filters = 'where '
while args:
- clave,valor = args.popitem()
- filters+=clave+' '+str(valor)
- filters+=' and ' if args else ''
+ clave, valor = args.popitem()
+ filters += clave + ' ' + str(valor)
+ filters += ' and ' if args else ''
c = con.cursor()
c.execute('BEGIN TRANSACTION')
- c.execute('SELECT id, priority, title, text, launched, expires, type, fav FROM notifications %s order by priority desc;' %filters)
+ c.execute('SELECT id, priority, title, text, launched, expires, type, fav FROM notifications %s order by priority desc;' % filters)
output = c.fetchall()
c.execute('END TRANSACTION')
self._close_connection(con)
@@ -142,10 +150,10 @@ class Store:
self.db = Db(db_filename)
# Borro todas las notificaciones que ya expiraron
# Para el futuro puede interesar tener un hisórico, habría que cambiar esto
- today = datetime.datetime.strftime(datetime.date.today(), "%Y-%m-%d")
- query = "delete from notifications where expires < %s;" %today
+ today = datetime.datetime.strftime(datetime.date.today(), "%Y-%m-%d")
+ query = "delete from notifications where expires < %s;" % today
self.db.run_query(query)
- # Implementado para futuras versiones
+ # Implementado para futuras versiones
"""
if not xmlpath:
xmlpath = os.path.join(env.get_data_root(),"mensajes.xml")
@@ -154,27 +162,28 @@ class Store:
fsock.close()
self.msg_list = self.xmldoc.getElementsByTagName("message")
"""
- # por el momento se implementa un parseo de los archivos shelve
- # de texto que se encuentren en /etc/notifier/data/tmp/
+ # por el momento se implementa un parseo de los archivos shelve
+ # de texto que se encuentren en /etc/notifier/data/tmp/
# obtengo todos los archivos que comiencen con 'notify_'
- xmlpath = '/tmp' # os.path.join(env.get_data_root(),'tmp')
- files = filter(lambda x: x.startswith("notify_"),os.listdir(xmlpath))
+ xmlpath = '/tmp' # os.path.join(env.get_data_root(),'tmp')
+ files = filter(lambda x: x.startswith("notify_"), os.listdir(xmlpath))
self.msg_list = {}
#msg_items = ['id', 'title', 'text', 'launched', 'expired', 'priority',]
for file in files:
- abspath = os.path.join(xmlpath,file)
+ abspath = os.path.join(xmlpath, file)
try:
f = shelve.open(abspath)
self._save_message(f)
f.close()
os.remove(abspath)
- except: pass
+ except:
+ pass
#for msg in self.msg_list:
# self._save_message(msg)
def _save_message(self, msg):
"""Procesa los mensajes que vienen en el diccionario msg"""
- print "procesando nodo %s" %msg["id"]
+ print "procesando nodo %s" % msg["id"]
keys = msg.keys()
values = []
for item in keys:
@@ -184,11 +193,11 @@ class Store:
def _save_XML_message(self, msg):
# For future releases
#TODO: Poder leer links html en el campo text
- print "procesando nodo %s" %msg.getAttribute("id")
+ print "procesando nodo %s" % msg.getAttribute("id")
refNode = msg.childNodes
- keys = ["id","type","priority"]
+ keys = ["id", "type", "priority"]
values = []
- map(lambda x: values.append(msg.getAttribute(x)),keys)
+ map(lambda x: values.append(msg.getAttribute(x)), keys)
for node in refNode:
if node.nodeType == 1:
#print "clave: %s, valor: %s" % (node.localName, node.firstChild.data)
@@ -196,7 +205,6 @@ class Store:
values.append(node.firstChild.wholeText.strip())
self.db.add_message(keys, values)
-
if __name__ == "__main__":
#db_filename = '../data/messages.db'
#xmlpath = "../data/mensajes.xml"