[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

authorGuillaume Vandevelde <gvandevelde@logilab.fr>
changeset67de0c9a883a
branchdefault
phasedraft
hiddenyes
parent revision#a4d465a3e77d fix(ci): manually remove the .tox/doc directory
child revision<not specified>
files modified by this revision
cubicweb/utils.py
# HG changeset patch
# User Guillaume Vandevelde <gvandevelde@logilab.fr>
# Date 1581094414 -3600
# Fri Feb 07 17:53:34 2020 +0100
# Node ID 67de0c9a883a54ff7ea1fd5c74fa495e93541000
# Parent a4d465a3e77d07cf6a79c121c10b2d6484cd7468
[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 --git a/cubicweb/utils.py b/cubicweb/utils.py
@@ -25,10 +25,11 @@
1  import random
2  import re
3  import json
4  from operator import itemgetter
5  from inspect import getfullargspec as getargspec
6 +from functools import wraps
7  from itertools import repeat
8  from uuid import uuid4
9  from threading import Lock
10  from logging import getLogger
11 
@@ -179,10 +180,24 @@
12          raise NotImplementedError
13      def pop(self, i):
14          self._size -= 1
15 
16 
17 +def handle_writing_constraints(method):
18 +    @wraps(method)
19 +    def wrapper(self, value):
20 +        if self.tracewrites:
21 +            from traceback import format_stack
22 +            stack = format_stack(None)[:-1]
23 +            escaped_stack = xml_escape(json_dumps(u'\n'.join(stack)))
24 +            escaped_html = xml_escape(value).replace('\n', '<br/>\n')
25 +            tpl = u'<span onclick="alert(%s)">%s</span>'
26 +            value = tpl % (escaped_stack, escaped_html)
27 +        return method(self, value)
28 +    return wrapper
29 +
30 +
31  class UStringIO(list):
32      """a file wrapper which automatically encode unicode string to an encoding
33      specifed in the constructor
34      """
35 
@@ -193,20 +208,18 @@
36      def __bool__(self):
37          return True
38 
39      __nonzero__ = __bool__
40 
41 +    @handle_writing_constraints
42      def write(self, value):
43 -        if self.tracewrites:
44 -            from traceback import format_stack
45 -            stack = format_stack(None)[:-1]
46 -            escaped_stack = xml_escape(json_dumps(u'\n'.join(stack)))
47 -            escaped_html = xml_escape(value).replace('\n', '<br/>\n')
48 -            tpl = u'<span onclick="alert(%s)">%s</span>'
49 -            value = tpl % (escaped_stack, escaped_html)
50          self.append(value)
51 
52 +    @handle_writing_constraints
53 +    def write_front(self, value):
54 +        self.insert(0, value)
55 +
56      def getvalue(self):
57          return u''.join(self)
58 
59      def __repr__(self):
60          return '<%s at %#x>' % (self.__class__.__name__, id(self))