utils.py: fix encode/decode_label py33
authorrobin
Wed, 27 Nov 2013 16:35:31 +0000
branchpy33
changeset 3850 52c3600611ec
parent 3849 8ff9b1fb92cd
child 3851 f7397fb50684
utils.py: fix encode/decode_label
src/reportlab/lib/utils.py
src/reportlab/platypus/doctemplate.py
src/reportlab/platypus/tableofcontents.py
--- a/src/reportlab/lib/utils.py	Wed Nov 27 15:18:57 2013 +0000
+++ b/src/reportlab/lib/utils.py	Wed Nov 27 16:35:31 2013 +0000
@@ -5,8 +5,11 @@
 __doc__='''Gazillions of miscellaneous internal utility functions'''
 
 import os, sys, imp, time
-import base64
-import pickle
+from base64 import decodestring as base64_decodestring, encodestring as base64_encodestring
+try:
+    from cPickle import dumps as pickle_dumps, loads as pickle_loads, dump as pickle_dump, load as pickle_load
+except ImportError:
+    from pickle import dumps as pickle_dumps, loads as pickle_loads, dump as pickle_dump, load as pickle_load
 from reportlab import isPy3
 from reportlab.lib.logger import warnOnce
 from reportlab.lib.rltempfile import get_rl_tempfile, get_rl_tempdir, _rl_getuid
@@ -84,6 +87,12 @@
             return x
         else:
             return str(x).encode(enc)
+
+    def encode_label(args):
+        return base64_encodestring(pickle_dumps(args)).strip().decode('latin1')
+
+    def decode_label(label):
+        return pickle_loads(base64_decodestring(label.encode('latin1')))
 else:
     if sys.hexversion >= 0x02000000:
         def _digester(s):
@@ -138,6 +147,12 @@
     def int2Byte(i):
         return chr(i)
 
+    def encode_label(args):
+        return base64_encodestring(pickle_dumps(args)).strip()
+
+    def decode_label(label):
+        return pickle_loads(base64_decodestring(label))
+
 def _findFiles(dirList,ext='.ttf'):
     from os.path import isfile, isdir, join as path_join
     from os import listdir
@@ -886,17 +901,17 @@
     def _dump(self,f):
         try:
             pos=f.tell()
-            pickle.dump(self.store,f)
+            pickle_dump(self.store,f)
         except:
             S=self.store.copy()
             ff=getBytesIO()
             for k,v in S.items():
                 try:
-                    pickle.dump({k:v},ff)
+                    pickle_dump({k:v},ff)
                 except:
                     S[k] = '<unpicklable object %r>' % v
             f.seek(pos,0)
-            pickle.dump(S,f)
+            pickle_dump(S,f)
 
     def dump(self):
         f = open(self.fn,'wb')
@@ -911,7 +926,7 @@
         return f.getvalue()
 
     def _load(self,f):
-        self.store = pickle.load(f)
+        self.store = pickle_load(f)
 
     def load(self):
         f = open(self.fn,'rb')
@@ -1250,18 +1265,6 @@
     data = data.replace("&amp;gt;", "&gt;")
     data = data.replace("&amp;lt;", "&lt;")
     return data
-
-def encode_label(args):
-    s = base64.encodestring(pickle.dumps(args)).strip()
-    if not isStr(s):
-        s = s.decode('utf-8')
-    return s
-
-def decode_label(label):
-    if isUnicode(label):
-        label = label.encode('utf-8')
-    v = pickle.loads(base64.decodestring(label))
-    return v
     
 class IdentStr(str):
     '''useful for identifying things that get split'''
--- a/src/reportlab/platypus/doctemplate.py	Wed Nov 27 15:18:57 2013 +0000
+++ b/src/reportlab/platypus/doctemplate.py	Wed Nov 27 16:35:31 2013 +0000
@@ -35,20 +35,12 @@
 from reportlab.rl_config import defaultPageSize, verbose
 import reportlab.lib.sequencer
 from reportlab.pdfgen import canvas
-from reportlab.lib.utils import isSeq
+from reportlab.lib.utils import isSeq, encode_label, decode_label
 try:
     set
 except NameError:
     from sets import Set as set
 
-from base64 import encodestring, decodestring
-try:
-    import pickle as pickle
-except ImportError:
-    import pickle
-dumps = pickle.dumps
-loads = pickle.loads
-
 import sys
 import logging
 logger = logging.getLogger("reportlab.platypus")
@@ -332,10 +324,10 @@
         self.data.append(args)
 
     def onDrawText(self,*args):
-        return '<onDraw name="%s" label="%s" />' % (self.name,encodestring(dumps(args)).strip())
+        return '<onDraw name="%s" label="%s" />' % (self.name,encode_label(args))
 
     def __call__(self,canv,kind,label):
-        self.add(*loads(decodestring(label)))
+        self.add(*decode_label(label))
 
     def attachToPageTemplate(self,pt):
         if pt.onPage:
@@ -374,7 +366,7 @@
         pass
 
     def onDrawStr(self,value,*args):
-        return onDrawStr(value,self,encodestring(dumps(args)).strip())
+        return onDrawStr(value,self,encode_label(args))
 
 class BaseDocTemplate:
     """
--- a/src/reportlab/platypus/tableofcontents.py	Wed Nov 27 15:18:57 2013 +0000
+++ b/src/reportlab/platypus/tableofcontents.py	Wed Nov 27 16:35:31 2013 +0000
@@ -46,7 +46,7 @@
 
 from reportlab.lib import enums
 from reportlab.lib.units import cm
-from reportlab.lib.utils import commasplit, escapeOnce
+from reportlab.lib.utils import commasplit, escapeOnce, encode_label, decode_label
 from reportlab.lib.styles import ParagraphStyle, _baseFontName
 from reportlab.platypus.paragraph import Paragraph
 from reportlab.platypus.doctemplate import IndexingFlowable
@@ -54,13 +54,6 @@
 from reportlab.platypus.flowables import Spacer, Flowable
 from reportlab.pdfbase.pdfmetrics import stringWidth
 from reportlab.pdfgen import canvas
-from base64 import encodestring, decodestring
-try:
-    import pickle as pickle
-except ImportError:
-    import pickle
-dumps = pickle.dumps
-loads = pickle.loads
 
 def unquote(txt):
     from xml.sax.saxutils import unescape
@@ -353,7 +346,7 @@
 
     def __call__(self,canv,kind,label):
         try:
-            terms, format, offset = loads(decodestring(label))
+            terms, format, offset = decode_label(label)
         except:
             terms = label
             format = offset = None
@@ -435,7 +428,7 @@
         def drawIndexEntryEnd(canvas, kind, label):
             '''Callback to draw dots and page numbers after each entry.'''
             style = self.getLevelStyle(leveloffset)
-            pages = loads(decodestring(label))
+            pages = decode_label(label)
             drawPageNumbers(canvas, style, pages, availWidth, availHeight, self.dot)
         self.canv.drawIndexEntryEnd = drawIndexEntryEnd
 
@@ -464,7 +457,7 @@
             if diff:
                 lastTexts = texts
                 texts = texts[i:]
-            label = encodestring(dumps(list(pageNumbers))).strip()
+            label = encode_label(list(pageNumbers))
             texts[-1] = '%s<onDraw name="drawIndexEntryEnd" label="%s"/>' % (texts[-1], label)
             for text in texts:
                 #Platypus and RML differ on how parsed XML attributes are escaped.