[cpif] r112 - trunk/frontend-web

svn at argo.es svn at argo.es
Thu May 31 20:11:30 CEST 2007


Author: alvaro
Date: Thu May 31 20:11:27 2007
New Revision: 112

Log:
Encapsulamiento de los skins.

Ahora todo se hace a traves de load_dict.

Para crear la lista de hilos se le pasa un diccionario
del tipo:

{"threads" : [ (timestamp_del_grupo,[
                  (id_hilo_1,
                   titulo,
                   timestamp_del_mensaje,
                   numero_de_mensajes,
                   punto_no_leido),
                  (id_hilo_2,
                   titulo,
                   timestamp_del_mensaje,
                   numero_de_mensajes,
                   punto_no_leido)]
                )
              ]
}



Modified:
   trunk/frontend-web/skins.py
   trunk/frontend-web/url_.py
   trunk/frontend-web/url_INVALIDA.py
   trunk/frontend-web/url_hilo.py
   trunk/frontend-web/url_nuevo_usuario.py
   trunk/frontend-web/url_nuevo_usuario_POST.py
   trunk/frontend-web/url_stop.py

Modified: trunk/frontend-web/skins.py
==============================================================================
--- trunk/frontend-web/skins.py	(original)
+++ trunk/frontend-web/skins.py	Thu May 31 20:11:27 2007
@@ -24,12 +24,13 @@
     }
 
 urls = {
-    '/':              ['group_date', 'threads'],
-    "/indice":        ['group_date', 'threads', 'previous_threads'],
-    '/hilo':          ['thread_entries'],
-    '/nuevo_usuario': ['new_user'],
-    '/error':         [],
-    '/stop':          []
+    '/':                    ['group_date', 'threads'],
+    "/indice":              ['group_date', 'threads', 'previous_threads'],
+    '/hilo':                ['thread_entries'],
+    '/nuevo_usuario':       ['new_user'],
+    '/error':               [],
+    '/stop':                [],
+    '/nuevo_usuario_POST':  []
     }
 
 import os
@@ -57,8 +58,8 @@
     self._tz=pytz.timezone("Europe/Madrid")
     self._skin="default"
     self._url=""
-    self._text = []
     self._style=["odd","even"]
+    self._text = []
     self._dict={
         "version": globales.version,
         "page_title": "cpif",
@@ -81,75 +82,65 @@
   def set_text(self,text):
     self._text.append(text)
 
-  def thread_prev(self,link):
-    if "thread_entries" in urls[self._url]:
-      self.set_text(available_skins[self._skin]['thread_prev'] % {'thread_prev':link})
-
-  def thread_num(self,link,num):
-    if "thread_entries" in urls[self._url]:
-      self.set_text(available_skins[self._skin]['thread_num'] % {'thread_num_link':link, 'thread_num':num})
-
-  def thread_next(self,link):
-    if "thread_entries" in urls[self._url]:
-      self.set_text(available_skins[self._skin]['thread_next'] % {'thread_next':link})
-
-  def thread_entries(self,e):
+  def thread(self):
     """Format some entries inside a thread"""
-    if "thread_entries" in urls[self._url]:
-      for msg_num,author,date,text in e:
-        format = self._style.pop(0)
-        self._style.append(format)
-        aux = available_skins[self._skin]['thread_entry'] % {"msg_num":msg_num, "author":author,
-                "date":hourdate(date,self._tz),
-                "text":text,"format":format }
-        self.set_text(aux)
-
-  def threads(self,t,notread,threads):
+    first_post, messages = self._dict.pop("messages")
+    for msg_num,author,date,text in messages:
+      format = self._style.pop(0)
+      self._style.append(format)
+      aux = available_skins[self._skin]['thread_entry'] % {"msg_num":msg_num, "author":author,
+          "date":hourdate(date,self._tz),
+          "text":text,"format":format }
+      self.set_text(aux)
+    
+    tl = self._dict.get('thread_prev',None)
+    if tl:
+      self.set_text(available_skins[self._skin]['thread_prev'] % {'thread_prev':tl})
+    tl = self._dict.get('thread_next',None)
+    if tl:
+      self.set_text(available_skins[self._skin]['thread_next'] % {'thread_next':tl})
+  
+  def list_threads(self):
     """Format the thread list"""
-    # FIXME: No me gusta pasarle el array entero de hilos para hacer la busqueda de la fecha
+    t_list = self._dict.pop("threads",None)
     thread_len=globales.thread_len
-    if "threads" in urls[self._url]:
-      for thread,title,not_read in t:
+    for date,threads in t_list:
+      self.set_text(available_skins[self._skin]['group_date'] % {'group_date':daydate(date,self._tz)})
+      for thread, title, ts, nr, nr_point in threads:
         format = self._style.pop(0)
         self._style.append(format)
-
-        ts=threads[thread]["TS"]
-        if not_read:
-          nr=notread[thread]
-          msg_num=threads[thread]["mensajes"][nr][0]
-          page=(msg_num-1)/thread_len
-          aux = available_skins[self._skin]['thread_unread'] % {"title":title,"thread":thread,"t_date":hourdate(ts,self._tz),"format": format,"page":page*thread_len+1,"notread":nr}
+        if nr:
+          page = (nr[0] - 1) / thread_len
+          aux = available_skins[self._skin]['thread_unread'] % {"title":title, "thread":thread, "t_date":hourdate(ts,self._tz), "format": format, "page":page*thread_len+1, "notread":nr_point}
         else:
           aux = available_skins[self._skin]['thread'] % {"title":title,"thread":thread,"t_date":hourdate(ts,self._tz),"format": format}
         self.set_text(aux)
-  
-  def group_date(self,date):
-    """Insert the thread date"""
-    if "group_date" in urls[self._url]:
-      self.set_text(available_skins[self._skin]['group_date'] % {'group_date':daydate(date,self._tz)})
 
-  def header(self):
-    return  available_skins[self._skin]['header'] % self._dict
+  def _header(self):
+    return available_skins[self._skin]['header'] % self._dict
   
-  def body(self,title=None):
+  def _body(self,title=None):
     if "previous_threads" in urls[self._url]:
       aux = available_skins[self._skin]['body_previous']
+      self.list_threads()
     elif "threads" in urls[self._url]:
       aux = available_skins[self._skin]['body']
+      self.list_threads()
     elif "thread_entries" in urls[self._url]:
       aux = available_skins[self._skin]['body_thread']
+      self.thread()
     elif "new_user" in urls[self._url]:
       aux = available_skins[self._skin]['new_user']
-    elif "stop" in urls[self._url]:
-      aux = available_skins[self._skin]['generic']
-    else:
+    else: # Removed the stop, error, etc urls from there, they (at the moment) are all tall the same
       aux = available_skins[self._skin]['generic']
+      self.set_text(self._dict.get('generic_message',None))
 
     ret = self._dict # Pillamos el diccionario a deolver
     ret['body'] = "\r\n".join(self._text) # Aniado el texto
-    self._text=[] # FIXME: Realmente necesario?
     return aux % ret
 
-  def footer(self):
+  def _footer(self):
     return available_skins[self._skin]['footer'] % self._dict
 
+  def web(self,code=200):
+    return code, "text/html; charset=utf-8", "\r\n".join([self._header(),self._body(),self._footer()])

Modified: trunk/frontend-web/url_.py
==============================================================================
--- trunk/frontend-web/url_.py	(original)
+++ trunk/frontend-web/url_.py	Thu May 31 20:11:27 2007
@@ -42,14 +42,18 @@
   import skins
   pagina = skins.Skin()
   pagina.load_url(path)
-  pagina.load_dict({"page_title": "cpif - listado de hilos"})
+  import calendario
+  dict = {
+      "page_title": "cpif - listado de hilos",
+      "threads":[],
+      "calendar": calendario.vista_mensual(conn,fecha_elegida,usuario)
+      }
 
   root=conn.get_root()
   hilos=root["hilos"]["hilos"]
   database.actualiza_no_leidos(conn,usuario)
   texto=[]
   num_hilos=0
-  estilos=["impar","par"]
   punto_no_leido=root["usuarios"]["usuarios"][database.normaliza_nick(usuario)]["punto de lectura no leidos"]
 
   while (num_hilos<50) and (fecha>=fecha_min) :
@@ -57,16 +61,19 @@
     h=database.listado_hilos_personal(conn,usuario,ts,ts2)
     l=len(h)
     if l :
-      pagina.group_date(ts2)
+      dict["threads"].append((ts2,[(
+        id, 
+        title,
+        hilos[id]["TS"], 
+        hilos[id]["mensajes"].get(punto_no_leido.get(id,None)), # El numero de mensajes hasta el no leido
+        punto_no_leido.get(id,None)) for id,title,not_read in h])) # El punto donde el usuario no ha leido
+
       num_hilos+=l
-      pagina.threads(h,punto_no_leido,hilos)
     ts=ts2
     fecha-=delta_dia
 
-  import calendario
-  pagina.load_dict({"calendar": calendario.vista_mensual(conn,fecha_elegida,usuario)})
-
-  return(200,"text/html; charset=utf-8","\r\n".join([pagina.header(),pagina.body(),pagina.footer()]))
+  pagina.load_dict(dict)
+  return(pagina.web())
 
 @monitor
 def init(conn) :

Modified: trunk/frontend-web/url_INVALIDA.py
==============================================================================
--- trunk/frontend-web/url_INVALIDA.py	(original)
+++ trunk/frontend-web/url_INVALIDA.py	Thu May 31 20:11:27 2007
@@ -7,6 +7,6 @@
   pagina = skins.Skin()
   pagina.load_url(['error'])
   pagina.load_dict({"page_title": "cpif - ERROR"})
-  pagina.set_text("<h2>ERROR<H2>\r\nLa pagina que buscas no existe, pich&oacute;n</h2>")
+  pagina.load_dict({"generic_message": "<h2>ERROR<H2>\r\nLa pagina que buscas no existe, pich&oacute;n</h2>"})
 
-  return (404,"text/html; charset=utf-8","\r\n".join([pagina.header(),pagina.body(),pagina.footer()]))
+  return (pagina.web(404))

Modified: trunk/frontend-web/url_hilo.py
==============================================================================
--- trunk/frontend-web/url_hilo.py	(original)
+++ trunk/frontend-web/url_hilo.py	Thu May 31 20:11:27 2007
@@ -27,23 +27,25 @@
   import skins 
   pagina = skins.Skin()
   pagina.load_url(path)
-  pagina.load_dict({"page_title":"cpif - %s" % meta["titulo"]})
 
-  pagina.load_dict({
+  dict = {
+      "page_title":"cpif - %s" % meta["titulo"],
       "thread_title": meta["titulo"],
       "thread_author": meta["creador"],
-      "msg_num": hilo_num
-      })
-  pagina.thread_entries(mensajes)
+      "msg_num": hilo_num,
+      "messages": (first_post,mensajes)
+      }
+
 
   if first_post!=1 :
     if first_post-1<=thread_len :
-      pagina.thread_prev("%d" % hilo_num) # FIXME especificar aqui el enlace /hilo/42?
+      dict["thread_prev"] =  "%d" % hilo_num # FIXME especificar aqui el enlace /hilo/42?
     else :
-      pagina.thread_prev("%d/%d" % (hilo_num,first_post-thread_len))
+      dict["thread_prev"] =  "%d/%d" % (hilo_num,first_post-thread_len)
   if not finished :
-    pagina.thread_next("%d/%d" % (hilo_num,first_post+thread_len))
+    dict["thread_next"] = "%d/%d" % (hilo_num,first_post+thread_len)
 
-  return(200,"text/html; charset=utf-8","\r\n".join([pagina.header(),pagina.body(),pagina.footer()]))
+  pagina.load_dict(dict)
+  return(pagina.web())
 
 

Modified: trunk/frontend-web/url_nuevo_usuario.py
==============================================================================
--- trunk/frontend-web/url_nuevo_usuario.py	(original)
+++ trunk/frontend-web/url_nuevo_usuario.py	Thu May 31 20:11:27 2007
@@ -10,6 +10,6 @@
 
   if usuario!="master" :
     pagina.load_url(["error"])
-    pagina.set_text("<h1>Solo el usuario 'master' puede dar de alta nuevos usuarios</h1>")
+    pagina.load_dict({"generic_message": "<h1>Solo el usuario 'master' puede dar de alta nuevos usuarios</h1>"})
 
-  return (200,"text/html; charset=utf-8","\r\n".join([pagina.header(),pagina.body(),pagina.footer()]))
+  return (pagina.web())

Modified: trunk/frontend-web/url_nuevo_usuario_POST.py
==============================================================================
--- trunk/frontend-web/url_nuevo_usuario_POST.py	(original)
+++ trunk/frontend-web/url_nuevo_usuario_POST.py	Thu May 31 20:11:27 2007
@@ -11,8 +11,8 @@
   
   if usuario!="master" :
     pagina.load_url(["error"])
-    pagina.set_text("<h1>Solo el usuario 'master' puede dar de alta nuevos usuarios</h1>")
-    return (200,"text/html; charset=utf-8","\r\n".join([pagina.header(),pagina.body(),pagina.footer()]))
+    pagina.load_dict({"generic_message": "<h1>Solo el usuario master puede crear nuevos usuarios</h1>"})
+    return (pagina.web())
 
   import cgi
   ctype,pdict=cgi.parse_header(handler.headers.getheader('content-type'))
@@ -23,23 +23,22 @@
 
   if not (nick and clave1 and clave2) :
     pagina.load_url(["error"])
-    pagina.set_text("<h1>No puedes dejar ningun campo en blanco</h1>")
-    return (200,"text/html; charset=utf-8","\r\n".join([pagina.header(),pagina.body(),pagina.footer()]))
+    pagina.load_dict({"generic_message": "<h1>No puedes dejar ningun campo en blanco</h1>"})
+    return (pagina.web())
 
   if clave1!=clave2 :
     pagina.load_url(["error"])
-    pagina.set_text("<h1>Las claves introducidas no coinciden</h1>")
-    return (200,"text/html; charset=utf-8","\r\n".join([pagina.header(),pagina.body(),pagina.footer()]))
+    pagina.load_dict({"generic_message": "<h1>Las claves introducinas no coinciden</h1>"})
+    return (pagina.web())
 
   import database
   if database.usuario_verifica(conn,nick=nick) :
     pagina.load_url(["error"])
-    pagina.set_text("<h1>El usuario ya existe</h1>")
-    return (200,"text/html; charset=utf-8","\r\n".join([pagina.header(),pagina.body(),pagina.footer()]))
+    pagina.load_dict({"generic_message": "<h1>El usuario ya existe</h1>"})
+    return (pagina.web())
 
   database.usuario_add(conn,nick,None,clave=clave1)
 
-  pagina.load_url(["error"])
-  pagina.set_text("<h1>Alta exitosa</h1>")
-  return (200,"text/html; charset=utf-8","\r\n".join([pagina.header(),pagina.body(),pagina.footer()]))
+  pagina.load_dict({"generic_message": "<h1>Alta exitosa</h1>"})
+  return (pagina.web())
 

Modified: trunk/frontend-web/url_stop.py
==============================================================================
--- trunk/frontend-web/url_stop.py	(original)
+++ trunk/frontend-web/url_stop.py	Thu May 31 20:11:27 2007
@@ -9,9 +9,9 @@
   pagina.load_dict({"page_title": "cpif - parando el servicio"})
 
   if usuario!="master" :
-    pagina.set_text("<h2>Solo el usuario 'master' puede parar el servicio</h2>")
+    pagina.load_dict({"generic_message": "<h2>Solo el usuario 'master' puede parar el servicio</h2>"})
   else:
     handler.must_stop=True
-    pagina.set_text("<h2>PARAMOS EL SERVICIO!!</h2>")
+    pagina.load_dict({"generic_message": "<h2>PARAMOS EL SERVICIO!!</h2>"})
 
-  return(200,"text/html; charset=utf-8","\r\n".join([pagina.header(),pagina.body(),pagina.footer()]))
+  return(pagina.web())



More information about the cpif mailing list