1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 __doc__ = \
21 """
22 pywurfl WURFL class hierarchy serializer
23 """
24
25 from time import ctime
26 from xml.etree.ElementTree import ElementTree, Element, SubElement
27
28 from pywurfl import __version__ as pw_version
29 from pywurfl.exceptions import WURFLException
30
31
32 __author__ = "Armand Lynch <lyncha@users.sourceforge.net>"
33 __copyright__ = "Copyright 2006-2010, Armand Lynch"
34 __license__ = "LGPL"
35 __url__ = "http://celljam.net/"
36 __all__ = ['Serialize']
37
38
41 self.root_device = devices.select_id('generic', instance=False)
42 self.common_caps = ['actual_device_root', 'children', 'devid', 'devua',
43 'groups', 'fall_back']
44 self.cap_groups = {}
45
47 group = self.cap_groups.get(cap)
48 if group is None:
49 for group in self.root_device.groups:
50 if cap in self.root_device.groups[group]:
51 self.cap_groups[cap] = group
52 return group
53 else:
54 msg = "'%s' capability does not belong to a generic group"
55 raise WURFLException(msg % cap)
56 return group
57
59 if isinstance(x, bool):
60 if x:
61 return "true"
62 else:
63 return "false"
64 if isinstance(x, (int, float, long)):
65 return str(x)
66 return x
67
68 - def _walk(self, device, devices):
69 new_dev = SubElement(devices, 'device')
70 new_dev.set('fall_back', device.fall_back)
71 new_dev.set('id', device.devid)
72 new_dev.set('user_agent', device.devua)
73 if device.actual_device_root:
74 new_dev.set('actual_device_root', 'true')
75
76 groups = {}
77 for cap in (c for c in device.__dict__ if c not in self.common_caps and
78 not c.startswith('_')):
79 value = self._get_value(getattr(device, cap))
80 try:
81 groups[self._find_group(cap)].append((cap, value))
82 except (AttributeError, KeyError):
83 groups[self._find_group(cap)] = [(cap, value)]
84
85
86 for group in groups:
87 new_group = SubElement(new_dev, 'group')
88 new_group.set('id', group)
89 for cap, value in groups[group]:
90 new_cap = SubElement(new_group, 'capability')
91 new_cap.set('name', cap)
92 new_cap.set('value', value)
93
94 for child in device.children:
95 self._walk(child, devices)
96
98 """
99 Serialize pywurfl's WURFL class hierarchy to xml
100
101 @param filename: The filename to save the hierarchy to
102 @type filename: string
103 """
104
105 root = Element('wurfl')
106 version = SubElement(root, 'version')
107 ver = SubElement(version, 'ver')
108 ver.text = "Generated by pywurfl v%s" % pw_version
109 last_updated = SubElement(version, 'last_updated')
110 last_updated.text = ctime()
111
112 devs = SubElement(root, 'devices')
113
114 self._walk(self.root_device, devs)
115
116 tree = ElementTree(root)
117 tree.write(filename)
118
119
120 if __name__ == '__main__':
121 from wurfl import devices
122 Serialize(devices).to_xml('my.xml')
123