-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxmlserializer.py
More file actions
259 lines (202 loc) · 8.09 KB
/
xmlserializer.py
File metadata and controls
259 lines (202 loc) · 8.09 KB
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
from importlib import import_module
from xml.etree.ElementTree import Element, tostring, XML
class XMLSerializerMixin(object):
"""
Provide serialize to xml functionality to inheriting classes.
Functions:
to_xml -- Dumps an object to its xml representation.
from_xml (static) -- Returns an object from the xml representation.
Private Functions:
_to_xml -- Does the `to_xml`'s actual job.
_to_xml_int -- Returns an int's object xml Element
_to_xml_str -- Returns an str's object xml Element
_to_xml_unicode -- Returns an str's object xml Element
_to_xml_dict -- Returns an dict's object xml Element
_to_xml_list -- Returns an list's object xml Element
_to_xml_tuple -- Returns an tuple's object xml Element
_to_xml_set -- Returns an set's object xml Element
_from_xml (static) -- Does the `from_xml`'s actual job.
_from_xml_int (static) -- Returns the int object from the xml Element
_from_xml_str (static) -- Returns the str object from the xml Element
_from_xml_unicode (static) -- Returns the str object from the xml Element
_from_xml_dict (static) -- Returns the dict object from the xml Element
_from_xml_list (static) -- Returns the list object from the xml Element
_from_xml_tuple (static) -- Returns the tuple object from the xml Element
_from_xml_set (static) -- Returns the set object from the xml Element
"""
def to_xml(self):
"""
Return the xml representation of the object as string.
"""
return tostring(self._to_xml(self))
def _to_xml(self, obj):
"""
Return the xml representation of any object as Element
Args:
obj -- the actual object to work with (can be an XMLSerializerMixin
or any class)
"""
xml = Element(obj.__class__.__name__)
xml.attrib['module'] = obj.__class__.__module__
for key in obj.__dict__:
value = obj.__dict__[key]
child = Element(key)
func = self._serializer_function(value)
child.append(func(value))
child[0].attrib['module'] = value.__class__.__module__
xml.append(child)
return xml
def _to_xml_int_and_str(self, obj):
"""
Return the xml Element of an int or a str.
Args:
obj -- the int or str to work with
"""
xml = Element(obj.__class__.__name__)
xml.attrib['module'] = obj.__class__.__module__
if obj.__class__.__name__ == 'unicode':
xml.text = unicode(obj)
else:
xml.text = str(obj)
return xml
_to_xml_int = _to_xml_str = _to_xml_unicode = _to_xml_int_and_str
def _to_xml_dict(self, obj):
"""
Return the xml Element of a dict.
Args:
obj -- the dictionary to work with
"""
xml = Element(obj.__class__.__name__)
xml.attrib['module'] = obj.__class__.__module__
for key in obj:
xml.append(Element('entry'))
child = xml[-1]
child.append(Element('key'))
func_key = self._serializer_function(key)
child[0].append(func_key(key))
child.append(Element('value'))
func_value = self._serializer_function(obj[key])
child[1].append(func_value(obj[key]))
return xml
def _to_xml_iterable(self, obj):
"""
Return the xml Element of a list or tuple.
Args:
obj -- the list or tuple to work with
"""
xml = Element(obj.__class__.__name__)
xml.attrib['module'] = obj.__class__.__module__
for elem in obj:
xml.append(Element('element'))
child = xml[-1]
func = self._serializer_function(elem)
child.append(func(elem))
return xml
_to_xml_list = _to_xml_tuple = _to_xml_iterable
def _serializer_function(self, obj):
"""
Return the function used for serializing the object
This method returns the method used to serialize the object
according to the object's class' name. If the method doesn't
exists, it returns the default `_to_xml` method.
Args:
obj -- the object that needs to be serialied
"""
try:
func = getattr(self, '_to_xml_' + obj.__class__.__name__)
except AttributeError:
func = self._to_xml
return func
@staticmethod
def from_xml(xml):
"""
Return the Python object retrieved from the xml.
Args:
xml -- the xml string to work with.
"""
return XMLSerializerMixin._from_xml(XML(xml))
@staticmethod
def _from_xml(parsed):
"""
Return the Python object retrieved from the parsed xml.
Args:
parsed -- the parsed xml received from `from_xml` function.
"""
module = import_module(parsed.attrib['module'])
cls = getattr(module, parsed.tag)
# Instantiate the class without calling it's constructor
obj = cls.__new__(cls)
for child in parsed:
try:
func = getattr(XMLSerializerMixin, '_from_xml_' + child[0].tag)
except AttributeError:
func = XMLSerializerMixin._from_xml
obj.__dict__[child.tag] = func(child[0])
return obj
@staticmethod
def _from_xml_int_and_str(parsed):
"""
Return the builtin `int` or `str` type from the xml.
Args:
parsed -- the parsed xml.
"""
module_name = parsed.attrib['module']
module = import_module(module_name)
cls = getattr(module, parsed.tag)
obj = cls(parsed.text)
return obj
_from_xml_int = _from_xml_str = _from_xml_unicode = _from_xml_int_and_str
@staticmethod
def _from_xml_dict(parsed):
"""
Return the builtin `dict` type from the xml.
Args:
parsed -- the parsed xml.
"""
module_name = parsed.attrib['module']
module = import_module(module_name)
cls = getattr(module, parsed.tag)
obj = {}
for child in parsed:
key = child.find('key')
func_key = XMLSerializerMixin._deserializer_function(key[0].tag)
value = child.find('value')
func_value = XMLSerializerMixin._deserializer_function(value[0].tag)
obj[func_key(key[0])] = func_value(value[0])
return obj
@staticmethod
def _from_xml_iterable(parsed):
"""
Return the builtin `list` or `tuple` type from the xml.
Args:
parsed -- the parsed xml.
"""
module_name = parsed.attrib['module']
module = import_module(module_name)
cls = getattr(module, parsed.tag)
obj = []
for child in parsed:
func = XMLSerializerMixin._deserializer_function(child[0].tag)
obj.append(func(child[0]))
return obj
_from_xml_list = _from_xml_iterable
_from_xml_tuple = staticmethod(
lambda parsed : tuple(XMLSerializerMixin._from_xml_iterable(parsed))
)
_from_xml_set = _from_xml_iterable
@staticmethod
def _deserializer_function(tag):
"""
Return the function used for de-serializing the xml element
This method returns the function used to de-serialize the xml
element according to its tag. If the function doesn't
exists, it returns the default `_from_xml` function.
Args:
obj -- the element's tag that needs to be de-serialied
"""
try:
func = getattr(XMLSerializerMixin,
'_from_xml_' + tag)
except AttributeError:
func = XMLSerializerMixin._from_xml
return func