-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchallenge-23-server.py
executable file
·62 lines (53 loc) · 1.71 KB
/
challenge-23-server.py
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
#!/usr/bin/python
# -*- coding: utf8 -*-
import xml.etree.cElementTree as ET
import simplejson
import SocketServer
def elem_to_internal(elem,strip=1):
"""Convert an Element into an internal dictionary (not JSON!)."""
d = {}
for key, value in elem.attrib.items():
d['@'+key] = value
# loop over subelements to merge them
for subelem in elem:
v = elem_to_internal(subelem,strip=strip)
tag = subelem.tag
value = v[tag]
try:
# add to existing list for this tag
d[tag].append(value)
except AttributeError:
# turn existing entry into a list
d[tag] = [d[tag], value]
except KeyError:
# add a new non-list entry
d[tag] = value
text = elem.text
tail = elem.tail
if strip:
# ignore leading and trailing whitespace
if text: text = text.strip()
if tail: tail = tail.strip()
if tail:
d['#tail'] = tail
if d:
# use #text element if other attributes exist
if text: d["#text"] = text
else:
# text is the value if no attributes
d = text or None
return {elem.tag: d}
def xml2json(xmlstring,strip=1):
elem = ET.fromstring(xmlstring)
if hasattr(elem, 'getroot'):
elem = elem.getroot()
return simplejson.dumps(elem_to_internal(elem,strip=strip))
class TCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
with open('unicode.xml') as f:
xmlString = f.read()
jsonString = xml2json(xmlString)
self.request.sendall(jsonString)
if __name__ == "__main__":
server = SocketServer.TCPServer(("localhost", 9999), TCPHandler)
server.serve_forever()