Pass the current session to sessiondata constructor.
[wrw.git] / wrw / sp / cons.py
... / ...
CommitLineData
1import xml.dom.minidom
2
3class node(object):
4 def __str__(self):
5 doc = xml.dom.minidom.Document()
6 return self.__todom__(doc).toxml()
7
8class text(node, unicode):
9 def __todom__(self, doc):
10 return doc.createTextNode(self)
11
12class raw(node, unicode):
13 def __todom__(self, doc):
14 raise Exception("Cannot convert raw code to DOM objects")
15
16class element(node):
17 def __init__(self, ns, name, ctx):
18 self.ns = ns
19 self.name = unicode(name)
20 self.ctx = ctx
21 self.attrs = {}
22 self.children = []
23
24 def __call__(self, *children, **attrs):
25 for child in children:
26 self.children.append(self.ctx.nodefrom(child))
27 for k, v in attrs.iteritems():
28 self.attrs[unicode(k)] = unicode(v)
29 return self
30
31 def __todom__(self, doc):
32 el = doc.createElementNS(self.ns, self.name)
33 for k, v in self.attrs.iteritems():
34 el.setAttribute(k, v)
35 for child in self.children:
36 el.appendChild(child.__todom__(doc))
37 return el
38
39class context(object):
40 def __init__(self):
41 self.nodeconv = {}
42 self.nodeconv[str] = lambda ob: text(ob, "utf-8")
43 self.nodeconv[unicode] = text
44 self.nodeconv[int] = text
45 self.nodeconv[long] = text
46 self.nodeconv[float] = text
47
48 def nodefrom(self, ob):
49 if isinstance(ob, node):
50 return ob
51 if hasattr(ob, "__tonode__"):
52 return ob.__tonode__()
53 if type(ob) in self.nodeconv:
54 return self.nodeconv[type(ob)](ob)
55 raise Exception("No node conversion known for %s objects" % str(type(ob)))
56
57class constructor(object):
58 def __init__(self, ns, elcls = element, ctx=None):
59 self._ns = ns
60 self._elcls = elcls
61 if ctx is None: ctx = context()
62 self._ctx = ctx
63
64 def __getattr__(self, name):
65 return self._elcls(self._ns, name, self._ctx)