[PATCH V2] [utils] Add the possibility to add elements in the head of an UStringIO list

Guillaume Vandevelde guillaume.vandevelde at logilab.fr
Wed Feb 12 11:02:51 CET 2020


# HG changeset patch
# User Guillaume Vandevelde <gvandevelde at logilab.fr>
# Date 1581094414 -3600
#      Fri Feb 07 17:53:34 2020 +0100
# Branch 3.27
# Node ID de83cd9ded312dca1fb4c68f36778048068d9406
# Parent  de90a96be6f0b2f808dbb7f0910b0badc6243496
# Available At http://hg.logilab.org/review/cubicweb
#              hg pull http://hg.logilab.org/review/cubicweb -r de83cd9ded31
[utils] Add the possibility to add elements in the head of an UStringIO list

This allows to place scripts on the front of the html head tag if needed

diff -r de90a96be6f0 -r de83cd9ded31 cubicweb/utils.py
--- a/cubicweb/utils.py	Sun Feb 02 22:15:38 2020 +0100
+++ b/cubicweb/utils.py	Fri Feb 07 17:53:34 2020 +0100
@@ -27,6 +27,7 @@
 import json
 from operator import itemgetter
 from inspect import getfullargspec as getargspec
+from functools import wraps
 from itertools import repeat
 from uuid import uuid4
 from threading import Lock
@@ -181,6 +182,20 @@
         self._size -= 1
 
 
+def handle_writing_constraints(method):
+    @wraps(method)
+    def wrapper(self, value):
+        if self.tracewrites:
+            from traceback import format_stack
+            stack = format_stack(None)[:-1]
+            escaped_stack = xml_escape(json_dumps(u'\n'.join(stack)))
+            escaped_html = xml_escape(value).replace('\n', '<br/>\n')
+            tpl = u'<span onclick="alert(%s)">%s</span>'
+            value = tpl % (escaped_stack, escaped_html)
+        return method(self, value)
+    return wrapper
+
+
 class UStringIO(list):
     """a file wrapper which automatically encode unicode string to an encoding
     specifed in the constructor
@@ -195,16 +210,14 @@
 
     __nonzero__ = __bool__
 
+    @handle_writing_constraints
     def write(self, value):
-        if self.tracewrites:
-            from traceback import format_stack
-            stack = format_stack(None)[:-1]
-            escaped_stack = xml_escape(json_dumps(u'\n'.join(stack)))
-            escaped_html = xml_escape(value).replace('\n', '<br/>\n')
-            tpl = u'<span onclick="alert(%s)">%s</span>'
-            value = tpl % (escaped_stack, escaped_html)
         self.append(value)
 
+    @handle_writing_constraints
+    def write_front(self, value):
+        self.insert(0, value)
+
     def getvalue(self):
         return u''.join(self)
 



More information about the cubicweb-devel mailing list