[cpif] r302 - in branches/heimy/frontend-web: . grammars

svn at argo.es svn at argo.es
Sat Jul 28 23:02:01 CEST 2007


Author: heimy
Date: Sat Jul 28 23:01:57 2007
New Revision: 302

Log:

* Anyadidos los atributos faltantes en los ficheros de grammars/
* Modificados url_nuevo_*_POST.py para usar grammars
* Creadas varias gramaticas mas
* TODO: Terminar las gramaticas y hacer tests de regresion



Added:
   branches/heimy/frontend-web/grammars/eol.py   (contents, props changed)
   branches/heimy/frontend-web/grammars/smileys.py   (contents, props changed)
   branches/heimy/frontend-web/grammars/urls.py   (contents, props changed)
Modified:
   branches/heimy/frontend-web/grammars/__init__.py   (contents, props changed)
   branches/heimy/frontend-web/grammars/bbcode.py   (contents, props changed)
   branches/heimy/frontend-web/grammars/nodes.py   (contents, props changed)
   branches/heimy/frontend-web/grammars/parser.py   (contents, props changed)
   branches/heimy/frontend-web/url_nuevo_hilo_POST.py
   branches/heimy/frontend-web/url_nuevo_post_POST.py

Modified: branches/heimy/frontend-web/grammars/__init__.py
==============================================================================
--- branches/heimy/frontend-web/grammars/__init__.py	(original)
+++ branches/heimy/frontend-web/grammars/__init__.py	Sat Jul 28 23:01:57 2007
@@ -1,4 +1,4 @@
-# $Id: __init__.py 266 2007-07-11 21:19:25Z heimy $
+# $Id$
 
 import os
 from nodes import TextNode, NodeList
@@ -12,7 +12,7 @@
 
     parser = Parser(grammar_list)
     parser.append(text)
-    return parser.parse().render_html()
+    return parser.parse()[0].render_html()
 
 def new_parser():
     global grammar_list
@@ -20,7 +20,7 @@
     return Parser(grammar_list)
 
 valid_grammar_mod = lambda x: x.endswith('.py') and x not in skip_list
-this_dir = os.path.dirname(__file__)
+this_dir = os.path.dirname(__file__) or '.'
 
 for grmr in (x for x in os.listdir(this_dir) if valid_grammar_mod(x)):
     try:

Modified: branches/heimy/frontend-web/grammars/bbcode.py
==============================================================================
--- branches/heimy/frontend-web/grammars/bbcode.py	(original)
+++ branches/heimy/frontend-web/grammars/bbcode.py	Sat Jul 28 23:01:57 2007
@@ -1,4 +1,4 @@
-# $Id: bbcode.py 266 2007-07-11 21:19:25Z heimy $
+# $Id$
 
 import re
 from nodes import Node, NodeList
@@ -37,7 +37,7 @@
             if type(lookup) == str:
                 if lookup in strng:
                     x1 = strng.find(lookup)
-                    lst.append( (x1, x1 + len(lookup), self, cls, fn) )
+                    lst.append( (x1, x1 + len(lookup) + 1, self, cls, fn) )
             else:
                 ret = lookup.search(strng)
                 if ret:

Added: branches/heimy/frontend-web/grammars/eol.py
==============================================================================
--- (empty file)
+++ branches/heimy/frontend-web/grammars/eol.py	Sat Jul 28 23:01:57 2007
@@ -0,0 +1,12 @@
+# $Id$
+
+from nodes import RawNode
+
+eol = "\r\n"
+
+class Grammar(object):
+    def search(self, text):
+        if "\r\n" in text:
+            x1 = text.find(eol)
+            return [(x1, x1 + len(eol), self, RawNode, RawNode, "<br />")]
+        return []

Modified: branches/heimy/frontend-web/grammars/nodes.py
==============================================================================
--- branches/heimy/frontend-web/grammars/nodes.py	(original)
+++ branches/heimy/frontend-web/grammars/nodes.py	Sat Jul 28 23:01:57 2007
@@ -1,32 +1,45 @@
-# $Id: nodes.py 266 2007-07-11 21:19:25Z heimy $
+# $Id$
 
-def escape_html(text):
-    text = text.replace('&', "&amp;")
-    text = text.replace('<', "&lt;")
-    text = text.replace('>', "&gt;")
-    text = text.replace('"', "&quot;")
-    text = text.replace("'", "&apos;")
-
-    return text
+import cgi
 
 class Node(object):
     def render_html(self):
         return ""
 
-class TextNode(Node):
-    def __init__(self, content):
+class EndNode(Node):
+    pass
+
+class RawNode(Node):
+    def __init__(self, parser, content):
         self.content = content
+    def render_html(self):
+        return self.content
 
+class TextNode(RawNode):
     def render_html(self):
-        return escape_html(self.content)
+        return cgi.escape(self.content)
 
 class AnchorNode(Node):
-    def __init__(self, parser, uri, content, *args, **kwarg):
+    def __init__(self, parser, uri, content, *args, **kw):
         self.uri = uri
-        self.content = parser.parse(content)
+        if 'no_recursive' not in kw:
+            self.content = parser.parse(content)
+        else:
+            self.content = RawNode(parser, content)
+            del(kw['no_recursive'])
+        self.kw = kw
 
     def render_html(self):
-        return "<a href='%s'>%s</a>" % (self.uri, self.content.render_html())
+        kwds = " ".join("%s='%s'" % (name, value) for (name, value) in self.kw.items())
+        return " ".join(["<a", kwds,
+                         "href='%s'>%s</a>" % (self.uri, self.content.render_html())])
+
+class ImgNode(Node):
+    def __init__(self, parser, src, **kw):
+        self.src, self.kw = src, kw
+    def render_html(self):
+        kwds = " ".join("%s='%s'" % (name, value) for (name, value) in self.kw.items)
+        return " ".join(["<img", kwds, "src='%s' />" % self.src])
 
 class NodeList(list, Node):
     def render_html(self):

Modified: branches/heimy/frontend-web/grammars/parser.py
==============================================================================
--- branches/heimy/frontend-web/grammars/parser.py	(original)
+++ branches/heimy/frontend-web/grammars/parser.py	Sat Jul 28 23:01:57 2007
@@ -1,4 +1,4 @@
-# $Id: __init__.py 266 2007-07-11 21:19:25Z heimy $
+# $Id$
 
 from nodes import TextNode, NodeList
 
@@ -39,14 +39,14 @@
             if not matches:
                 if until:
                     raise ParserException("Parser stopped while waiting for %s" % repr(until))
-                nl.append(TextNode(self.string))
+                nl.append(TextNode(self, self.string))
                 self.string = ""
                 continue
             next = sorted(matches)[0]
             # check if "next" is in "until"
             x1, x2, grm, cls, fn = next[:5]
             if x1 > 0:
-                nl.append(TextNode(self.string[:x1]))
+                nl.append(TextNode(self, self.string[:x1]))
             self.string = self.string[x2:]
             if cls in until:
                 stop = next[3]

Added: branches/heimy/frontend-web/grammars/smileys.py
==============================================================================
--- (empty file)
+++ branches/heimy/frontend-web/grammars/smileys.py	Sat Jul 28 23:01:57 2007
@@ -0,0 +1,29 @@
+# $Id$
+
+from globales import monitor
+from nodes import ImgNode
+
+try:
+    @monitor
+    def get_smiley_list(conn):
+      import database
+      return database.get_smiley_list(conn)
+
+    smiley_dict = dict(get_smiley_list())
+except TypeError: # in case monitor is not defined
+    smiley_dict = {}
+
+class SmileyNode(ImgNode):
+    def __init__(self, parser, symbol, sm_hash):
+        super(SmileyNode, self).__init__(parser,
+                                         "/static/smileys/" + sm_hash,
+                                         alt = symbol)
+
+class Grammar(object):
+    def search(self, text):
+        lst = []
+        for sm, sm_hash in smiley_dict.items():
+            if sm in text:
+                x1 = text.find(sm)
+                lst.append( (x1, x1 + len(sm), self, SmileyNode, SmileyNode, sm, sm_hash) )
+        return lst

Added: branches/heimy/frontend-web/grammars/urls.py
==============================================================================
--- (empty file)
+++ branches/heimy/frontend-web/grammars/urls.py	Sat Jul 28 23:01:57 2007
@@ -0,0 +1,37 @@
+# $Id$
+
+from nodes import AnchorNode
+import re
+
+## ...BEG... Codigo original de alvaro
+
+# Everybody stand back!!!
+domain = r"[a-zA-Z]{2,4}"
+subdomain = r"(?:[a-zA-Z0-9_\-]+\.)+"
+string = r"(?:[a-zA-Z0-9_\-]+)+"
+port = r"(?:\:[0-9]+)?"
+document = r"(?:/\S+)*"
+
+allowed_urls = [
+    '(?:http|ftp)://'+subdomain+domain+port+document+'/{0,1}',
+    'mailto:'+string+"@"+subdomain+domain,
+    ]
+
+## ...END... Codigo original de alvaro
+
+valid_url = re.compile("|".join("(\s|\A)(%s)(\s|\Z)" % i for i in allowed_urls))
+
+def url_o_matic(url):
+  return """<a href="%(url)s" title="%(url)s">%(url)s</a>""" % locals()
+
+def do_url(parser, ret):
+    uri = reduce(lambda x,y: (x if x.strip() else y), ret.groups())
+    return AnchorNode(parser, uri, uri, title=uri, no_recursive = True)
+
+class Grammar(object):
+    def search(self, text):
+        ret = valid_url.search(text)
+        if ret:
+            x1, x2 = ret.span()
+            return [ (x1 + 1, x2 - 1, self, AnchorNode, do_url, ret) ]
+        return []

Modified: branches/heimy/frontend-web/url_nuevo_hilo_POST.py
==============================================================================
--- branches/heimy/frontend-web/url_nuevo_hilo_POST.py	(original)
+++ branches/heimy/frontend-web/url_nuevo_hilo_POST.py	Sat Jul 28 23:01:57 2007
@@ -2,9 +2,10 @@
 
 from globales import monitor
 
-import parsers # Doing here outside to avoid "monitor" deadlocks
+import grammars # Doing here outside to avoid "monitor" deadlocks
+from grammars.parser import ParserException
 
-def pagina_error(texto) :
+def pagina_error(path,usuario,texto) :
   import skins
   pagina = skins.Skin(path,usuario)
   pagina.load_dict({"page_title": "Error"})
@@ -32,13 +33,14 @@
   titulo=cuerpo.getfirst("titulo")
   texto=cuerpo.getfirst("texto")
   if not (titulo and texto)  : # Incluye tanto el caso de vacios como de inexistentes
-    return pagina_error("El T&iacute;tulo y el Texto no pueden estar vacios")
+    return pagina_error(path,usuario,"El T&iacute;tulo y el Texto no pueden estar vacios")
 
   titulo=cgi.escape(titulo)
 
-  error,texto2=parsers.convert_to_html(texto)
-  if error :
-    return (200,{"Content-Type":"text/plain; charset=utf-8"},error)
+  try:
+    texto2=grammars.parse_to_html(texto)
+  except ParserException, p:
+    return (200,{"Content-Type":"text/plain; charset=utf-8"}, str(p))
   database.mensaje_add(conn,texto,texto2,usuario,titulo=titulo,metatag=metatag)
   return (302,{"Location":"/indice/%d" %metatag},"")
 

Modified: branches/heimy/frontend-web/url_nuevo_post_POST.py
==============================================================================
--- branches/heimy/frontend-web/url_nuevo_post_POST.py	(original)
+++ branches/heimy/frontend-web/url_nuevo_post_POST.py	Sat Jul 28 23:01:57 2007
@@ -2,9 +2,10 @@
 
 from globales import monitor
 
-import parsers # Doing here outside to avoid "monitor" deadlocks
+import grammars # Doing here outside to avoid "monitor" deadlocks
+from grammars.parser import ParserException
 
-def pagina_error(texto) :
+def pagina_error(path,usuario,texto) :
   import skins
   pagina = skins.Skin(path,usuario)
   pagina.load_dict({"page_title": "Error"})
@@ -32,11 +33,12 @@
   cuerpo=cgi.FieldStorage(fp=handler.rfile,headers=handler.headers,environ={'REQUEST_METHOD':'POST'},keep_blank_values=1)
   texto=cuerpo.getfirst("texto")
   if not texto : # Incluye tanto el caso de vacio como de inexistente
-    return pagina_error("El Texto no puede estar vacio")
+    return pagina_error(path,usuario,"El Texto no puede estar vacio")
 
-  error,texto2=parsers.convert_to_html(texto)
-  if error :
-    return (200,{"Content-Type":"text/plain; charset=utf-8"},error)
+  try:
+    texto2=grammars.parse_to_html(texto)
+  except ParserException, p:
+    return (200,{"Content-Type":"text/plain; charset=utf-8"}, str(p))
   database.mensaje_add(conn,texto,texto2,usuario,hilo=hilo)
   return (302,{"Location":"/indice/%d" %metatag}, "")
 



More information about the cpif mailing list