PageRenderTime 48ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/py/_xmlgen.py

https://bitbucket.org/evelyn559/pypy
Python | 244 lines | 231 code | 7 blank | 6 comment | 8 complexity | b8a628a371cd129d1d6e714cc0503391 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 "".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. def object(self, obj):
  112. #self.write(obj)
  113. self.write(escape(unicode(obj)))
  114. def raw(self, obj):
  115. self.write(obj.uniobj)
  116. def list(self, obj):
  117. assert id(obj) not in self.visited
  118. self.visited[id(obj)] = 1
  119. map(self.visit, obj)
  120. def Tag(self, tag):
  121. assert id(tag) not in self.visited
  122. try:
  123. tag.parent = self.parents[-1]
  124. except IndexError:
  125. tag.parent = None
  126. self.visited[id(tag)] = 1
  127. tagname = getattr(tag, 'xmlname', tag.__class__.__name__)
  128. if self.curindent and not self._isinline(tagname):
  129. self.write("\n" + u(' ') * self.curindent)
  130. if tag:
  131. self.curindent += self.indent
  132. self.write(u('<%s%s>') % (tagname, self.attributes(tag)))
  133. self.parents.append(tag)
  134. for x in tag:
  135. self.visit(x)
  136. self.parents.pop()
  137. self.write(u('</%s>') % tagname)
  138. self.curindent -= self.indent
  139. else:
  140. nameattr = tagname+self.attributes(tag)
  141. if self._issingleton(tagname):
  142. self.write(u('<%s/>') % (nameattr,))
  143. else:
  144. self.write(u('<%s></%s>') % (nameattr, tagname))
  145. def attributes(self, tag):
  146. # serialize attributes
  147. attrlist = dir(tag.attr)
  148. attrlist.sort()
  149. l = []
  150. for name in attrlist:
  151. res = self.repr_attribute(tag.attr, name)
  152. if res is not None:
  153. l.append(res)
  154. l.extend(self.getstyle(tag))
  155. return u("").join(l)
  156. def repr_attribute(self, attrs, name):
  157. if name[:2] != '__':
  158. value = getattr(attrs, name)
  159. if name.endswith('_'):
  160. name = name[:-1]
  161. return ' %s="%s"' % (name, escape(unicode(value)))
  162. def getstyle(self, tag):
  163. """ return attribute list suitable for styling. """
  164. try:
  165. styledict = tag.style.__dict__
  166. except AttributeError:
  167. return []
  168. else:
  169. stylelist = [x+': ' + y for x,y in styledict.items()]
  170. return [u(' style="%s"') % u('; ').join(stylelist)]
  171. def _issingleton(self, tagname):
  172. """can (and will) be overridden in subclasses"""
  173. return self.shortempty
  174. def _isinline(self, tagname):
  175. """can (and will) be overridden in subclasses"""
  176. return False
  177. class HtmlVisitor(SimpleUnicodeVisitor):
  178. single = dict([(x, 1) for x in
  179. ('br,img,area,param,col,hr,meta,link,base,'
  180. 'input,frame').split(',')])
  181. inline = dict([(x, 1) for x in
  182. ('a abbr acronym b basefont bdo big br cite code dfn em font '
  183. 'i img input kbd label q s samp select small span strike '
  184. 'strong sub sup textarea tt u var'.split(' '))])
  185. def repr_attribute(self, attrs, name):
  186. if name == 'class_':
  187. value = getattr(attrs, name)
  188. if value is None:
  189. return
  190. return super(HtmlVisitor, self).repr_attribute(attrs, name)
  191. def _issingleton(self, tagname):
  192. return tagname in self.single
  193. def _isinline(self, tagname):
  194. return tagname in self.inline
  195. class _escape:
  196. def __init__(self):
  197. self.escape = {
  198. u('"') : u('&quot;'), u('<') : u('&lt;'), u('>') : u('&gt;'),
  199. u('&') : u('&amp;'), u("'") : u('&apos;'),
  200. }
  201. self.charef_rex = re.compile(u("|").join(self.escape.keys()))
  202. def _replacer(self, match):
  203. return self.escape[match.group(0)]
  204. def __call__(self, ustring):
  205. """ xml-escape the given unicode string. """
  206. ustring = unicode(ustring)
  207. return self.charef_rex.sub(self._replacer, ustring)
  208. escape = _escape()