PageRenderTime 46ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/py/_xmlgen.py

https://bitbucket.org/pwaller/pypy
Python | 251 lines | 238 code | 7 blank | 6 comment | 8 complexity | 580431aba423c89b0426d16b2d2c1bc8 MD5 | raw file
  1. """
  2. module for generating and serializing xml and html structures
  3. by using simple python objects.
  4. (c) holger krekel, holger at merlinux eu. 2009
  5. """
  6. import py
  7. import sys, re
  8. if sys.version_info >= (3,0):
  9. def u(s):
  10. return s
  11. def unicode(x):
  12. if hasattr(x, '__unicode__'):
  13. return x.__unicode__()
  14. return str(x)
  15. else:
  16. def u(s):
  17. return unicode(s)
  18. unicode = unicode
  19. class NamespaceMetaclass(type):
  20. def __getattr__(self, name):
  21. if name[:1] == '_':
  22. raise AttributeError(name)
  23. if self == Namespace:
  24. raise ValueError("Namespace class is abstract")
  25. tagspec = self.__tagspec__
  26. if tagspec is not None and name not in tagspec:
  27. raise AttributeError(name)
  28. classattr = {}
  29. if self.__stickyname__:
  30. classattr['xmlname'] = name
  31. cls = type(name, (self.__tagclass__,), classattr)
  32. setattr(self, name, cls)
  33. return cls
  34. class Tag(list):
  35. class Attr(object):
  36. def __init__(self, **kwargs):
  37. self.__dict__.update(kwargs)
  38. def __init__(self, *args, **kwargs):
  39. super(Tag, self).__init__(args)
  40. self.attr = self.Attr(**kwargs)
  41. def __unicode__(self):
  42. return self.unicode(indent=0)
  43. __str__ = __unicode__
  44. def unicode(self, indent=2):
  45. l = []
  46. SimpleUnicodeVisitor(l.append, indent).visit(self)
  47. return u("").join(l)
  48. def __repr__(self):
  49. name = self.__class__.__name__
  50. return "<%r tag object %d>" % (name, id(self))
  51. Namespace = NamespaceMetaclass('Namespace', (object, ), {
  52. '__tagspec__': None,
  53. '__tagclass__': Tag,
  54. '__stickyname__': False,
  55. })
  56. class HtmlTag(Tag):
  57. def unicode(self, indent=2):
  58. l = []
  59. HtmlVisitor(l.append, indent, shortempty=False).visit(self)
  60. return u("").join(l)
  61. # exported plain html namespace
  62. class html(Namespace):
  63. __tagclass__ = HtmlTag
  64. __stickyname__ = True
  65. __tagspec__ = dict([(x,1) for x in (
  66. 'a,abbr,acronym,address,applet,area,b,bdo,big,blink,'
  67. 'blockquote,body,br,button,caption,center,cite,code,col,'
  68. 'colgroup,comment,dd,del,dfn,dir,div,dl,dt,em,embed,'
  69. 'fieldset,font,form,frameset,h1,h2,h3,h4,h5,h6,head,html,'
  70. 'i,iframe,img,input,ins,kbd,label,legend,li,link,listing,'
  71. 'map,marquee,menu,meta,multicol,nobr,noembed,noframes,'
  72. 'noscript,object,ol,optgroup,option,p,pre,q,s,script,'
  73. 'select,small,span,strike,strong,style,sub,sup,table,'
  74. 'tbody,td,textarea,tfoot,th,thead,title,tr,tt,u,ul,xmp,'
  75. 'base,basefont,frame,hr,isindex,param,samp,var'
  76. ).split(',') if x])
  77. class Style(object):
  78. def __init__(self, **kw):
  79. for x, y in kw.items():
  80. x = x.replace('_', '-')
  81. setattr(self, x, y)
  82. class raw(object):
  83. """just a box that can contain a unicode string that will be
  84. included directly in the output"""
  85. def __init__(self, uniobj):
  86. self.uniobj = uniobj
  87. class SimpleUnicodeVisitor(object):
  88. """ recursive visitor to write unicode. """
  89. def __init__(self, write, indent=0, curindent=0, shortempty=True):
  90. self.write = write
  91. self.cache = {}
  92. self.visited = {} # for detection of recursion
  93. self.indent = indent
  94. self.curindent = curindent
  95. self.parents = []
  96. self.shortempty = shortempty # short empty tags or not
  97. def visit(self, node):
  98. """ dispatcher on node's class/bases name. """
  99. cls = node.__class__
  100. try:
  101. visitmethod = self.cache[cls]
  102. except KeyError:
  103. for subclass in cls.__mro__:
  104. visitmethod = getattr(self, subclass.__name__, None)
  105. if visitmethod is not None:
  106. break
  107. else:
  108. visitmethod = self.__object
  109. self.cache[cls] = visitmethod
  110. visitmethod(node)
  111. # the default fallback handler is marked private
  112. # to avoid clashes with the tag name object
  113. def __object(self, obj):
  114. #self.write(obj)
  115. self.write(escape(unicode(obj)))
  116. def raw(self, obj):
  117. self.write(obj.uniobj)
  118. def list(self, obj):
  119. assert id(obj) not in self.visited
  120. self.visited[id(obj)] = 1
  121. for elem in obj:
  122. self.visit(elem)
  123. def Tag(self, tag):
  124. assert id(tag) not in self.visited
  125. try:
  126. tag.parent = self.parents[-1]
  127. except IndexError:
  128. tag.parent = None
  129. self.visited[id(tag)] = 1
  130. tagname = getattr(tag, 'xmlname', tag.__class__.__name__)
  131. if self.curindent and not self._isinline(tagname):
  132. self.write("\n" + u(' ') * self.curindent)
  133. if tag:
  134. self.curindent += self.indent
  135. self.write(u('<%s%s>') % (tagname, self.attributes(tag)))
  136. self.parents.append(tag)
  137. for x in tag:
  138. self.visit(x)
  139. self.parents.pop()
  140. self.write(u('</%s>') % tagname)
  141. self.curindent -= self.indent
  142. else:
  143. nameattr = tagname+self.attributes(tag)
  144. if self._issingleton(tagname):
  145. self.write(u('<%s/>') % (nameattr,))
  146. else:
  147. self.write(u('<%s></%s>') % (nameattr, tagname))
  148. def attributes(self, tag):
  149. # serialize attributes
  150. attrlist = dir(tag.attr)
  151. attrlist.sort()
  152. l = []
  153. for name in attrlist:
  154. res = self.repr_attribute(tag.attr, name)
  155. if res is not None:
  156. l.append(res)
  157. l.extend(self.getstyle(tag))
  158. return u("").join(l)
  159. def repr_attribute(self, attrs, name):
  160. if name[:2] != '__':
  161. value = getattr(attrs, name)
  162. if name.endswith('_'):
  163. name = name[:-1]
  164. if isinstance(value, raw):
  165. insert = value.uniobj
  166. else:
  167. insert = escape(unicode(value))
  168. return ' %s="%s"' % (name, insert)
  169. def getstyle(self, tag):
  170. """ return attribute list suitable for styling. """
  171. try:
  172. styledict = tag.style.__dict__
  173. except AttributeError:
  174. return []
  175. else:
  176. stylelist = [x+': ' + y for x,y in styledict.items()]
  177. return [u(' style="%s"') % u('; ').join(stylelist)]
  178. def _issingleton(self, tagname):
  179. """can (and will) be overridden in subclasses"""
  180. return self.shortempty
  181. def _isinline(self, tagname):
  182. """can (and will) be overridden in subclasses"""
  183. return False
  184. class HtmlVisitor(SimpleUnicodeVisitor):
  185. single = dict([(x, 1) for x in
  186. ('br,img,area,param,col,hr,meta,link,base,'
  187. 'input,frame').split(',')])
  188. inline = dict([(x, 1) for x in
  189. ('a abbr acronym b basefont bdo big br cite code dfn em font '
  190. 'i img input kbd label q s samp select small span strike '
  191. 'strong sub sup textarea tt u var'.split(' '))])
  192. def repr_attribute(self, attrs, name):
  193. if name == 'class_':
  194. value = getattr(attrs, name)
  195. if value is None:
  196. return
  197. return super(HtmlVisitor, self).repr_attribute(attrs, name)
  198. def _issingleton(self, tagname):
  199. return tagname in self.single
  200. def _isinline(self, tagname):
  201. return tagname in self.inline
  202. class _escape:
  203. def __init__(self):
  204. self.escape = {
  205. u('"') : u('&quot;'), u('<') : u('&lt;'), u('>') : u('&gt;'),
  206. u('&') : u('&amp;'), u("'") : u('&apos;'),
  207. }
  208. self.charef_rex = re.compile(u("|").join(self.escape.keys()))
  209. def _replacer(self, match):
  210. return self.escape[match.group(0)]
  211. def __call__(self, ustring):
  212. """ xml-escape the given unicode string. """
  213. ustring = unicode(ustring)
  214. return self.charef_rex.sub(self._replacer, ustring)
  215. escape = _escape()