Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorEsteban Bordon <ebordon@plan.ceibal.edu.uy>2012-04-26 11:44:32 (GMT)
committer Esteban Bordon <ebordon@plan.ceibal.edu.uy>2012-04-26 11:44:32 (GMT)
commitc80e7322a19356056f1b335a513ebba2b9dd1f0c (patch)
treeed949c1676fb58e34ff67e890a5d8f4e55bdefb3
parent1440258b5c6e4c49c6462cbef8d75770c16770b6 (diff)
store.py con función get_categories que obtiene el conjunto de categorías disponibles
-rw-r--r--store.py84
1 files changed, 42 insertions, 42 deletions
diff --git a/store.py b/store.py
index f6d89e0..fd865fb 100644
--- a/store.py
+++ b/store.py
@@ -15,35 +15,27 @@ 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
@@ -56,9 +48,9 @@ class Db:
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)
@@ -68,12 +60,20 @@ class Db:
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)
+ except sqlite3.IntegrityError,e:
+ print "Error al eliminar datos: %s" %str(e)
c.execute('END TRANSACTION')
self._close_connection(con)
+ def get_categories(self, order='+'):
+ if order == '+':
+ order = "ASC"
+ else:
+ 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 +81,15 @@ class Db:
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))
+ 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 bool(int(fav[0]['fav']))
+ fav = self.run_query("select fav from notifications where id=%i" %id_msg)
+ return fav[0]['fav']
def run_query(self, query):
"""
@@ -113,12 +113,12 @@ class Db:
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 +142,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,28 +154,27 @@ 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:
@@ -185,11 +184,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)
@@ -197,6 +196,7 @@ 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"