1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
|
"""Python implementation of the htmltext type, the htmlescape function and
TemplateIO.
"""
#$HeadURL: svn+ssh://svn/repos/trunk/quixote/_py_htmltext.py $
#$Id: _py_htmltext.py 25234 2004-09-30 17:36:19Z nascheme $
import sys
from types import UnicodeType, TupleType, StringType, IntType, FloatType, \
LongType
import re
if sys.hexversion < 0x20200b1:
# 2.2 compatibility hacks
class object:
pass
def classof(o):
if hasattr(o, "__class__"):
return o.__class__
else:
return type(o)
else:
classof = type
_format_codes = 'diouxXeEfFgGcrs%'
_format_re = re.compile(r'%%[^%s]*[%s]' % (_format_codes, _format_codes))
def _escape_string(s):
if not isinstance(s, StringType):
raise TypeError, 'string required'
s = s.replace("&", "&")
s = s.replace("<", "<")
s = s.replace(">", ">")
s = s.replace('"', """)
return s
class htmltext(object):
"""The htmltext string-like type. This type serves as a tag
signifying that HTML special characters do not need to be escaped
using entities.
"""
__slots__ = ['s']
def __init__(self, s):
self.s = str(s)
# XXX make read-only
#def __setattr__(self, name, value):
# raise AttributeError, 'immutable object'
def __getstate__(self):
raise ValueError, 'htmltext objects should not be pickled'
def __repr__(self):
return '<htmltext %r>' % self.s
def __str__(self):
return self.s
def __len__(self):
return len(self.s)
def __cmp__(self, other):
return cmp(self.s, other)
def __hash__(self):
return hash(self.s)
def __mod__(self, args):
codes = []
usedict = 0
for format in _format_re.findall(self.s):
if format[-1] != '%':
if format[1] == '(':
usedict = 1
codes.append(format[-1])
if usedict:
args = _DictWrapper(args)
else:
if len(codes) == 1 and not isinstance(args, TupleType):
args = (args,)
args = tuple([_wraparg(arg) for arg in args])
return self.__class__(self.s % args)
def __add__(self, other):
if isinstance(other, StringType):
return self.__class__(self.s + _escape_string(other))
elif classof(other) is self.__class__:
return self.__class__(self.s + other.s)
else:
return NotImplemented
def __radd__(self, other):
if isinstance(other, StringType):
return self.__class__(_escape_string(other) + self.s)
else:
return NotImplemented
def __mul__(self, n):
return self.__class__(self.s * n)
def join(self, items):
quoted_items = []
for item in items:
if classof(item) is self.__class__:
quoted_items.append(str(item))
elif isinstance(item, StringType):
quoted_items.append(_escape_string(item))
else:
raise TypeError(
'join() requires string arguments (got %r)' % item)
return self.__class__(self.s.join(quoted_items))
def startswith(self, s):
if isinstance(s, htmltext):
s = s.s
else:
s = _escape_string(s)
return self.s.startswith(s)
def endswith(self, s):
if isinstance(s, htmltext):
s = s.s
else:
s = _escape_string(s)
return self.s.endswith(s)
def replace(self, old, new, maxsplit=-1):
if isinstance(old, htmltext):
old = old.s
else:
old = _escape_string(old)
if isinstance(new, htmltext):
new = new.s
else:
new = _escape_string(new)
return self.__class__(self.s.replace(old, new))
def lower(self):
return self.__class__(self.s.lower())
def upper(self):
return self.__class__(self.s.upper())
def capitalize(self):
return self.__class__(self.s.capitalize())
class _QuoteWrapper(object):
# helper for htmltext class __mod__
__slots__ = ['value', 'escape']
def __init__(self, value, escape):
self.value = value
self.escape = escape
def __str__(self):
return self.escape(str(self.value))
def __repr__(self):
return self.escape(`self.value`)
class _DictWrapper(object):
def __init__(self, value):
self.value = value
def __getitem__(self, key):
return _wraparg(self.value[key])
def _wraparg(arg):
if (classof(arg) is htmltext or
isinstance(arg, IntType) or
isinstance(arg, LongType) or
isinstance(arg, FloatType)):
# ints, longs, floats, and htmltext are okay
return arg
else:
# everything is gets wrapped
return _QuoteWrapper(arg, _escape_string)
def htmlescape(s):
"""htmlescape(s) -> htmltext
Return an 'htmltext' object using the argument. If the argument is not
already a 'htmltext' object then the HTML markup characters \", <, >,
and & are first escaped.
"""
if classof(s) is htmltext:
return s
elif isinstance(s, UnicodeType):
s = s.encode('iso-8859-1')
else:
s = str(s)
# inline _escape_string for speed
s = s.replace("&", "&") # must be done first
s = s.replace("<", "<")
s = s.replace(">", ">")
s = s.replace('"', """)
return htmltext(s)
class TemplateIO(object):
"""Collect output for PTL scripts.
"""
__slots__ = ['html', 'data']
def __init__(self, html=0):
self.html = html
self.data = []
def __iadd__(self, other):
if other is not None:
self.data.append(other)
return self
def __repr__(self):
return ("<%s at %x: %d chunks>" %
(self.__class__.__name__, id(self), len(self.data)))
def __str__(self):
return str(self.getvalue())
def getvalue(self):
if self.html:
return htmltext('').join(map(htmlescape, self.data))
else:
return ''.join(map(str, self.data))
|