source: branches/active/character_customization/game/parpg/serializers.py @ 774

Revision 774, 5.0 KB checked in by aspidites, 9 years ago (diff)

Patch by Aspidites

  • removed shebang from all python files except launcher scripts
  • added shebang to pychan_designer
Line 
1#   This file is part of PARPG.
2
3#   PARPG is free software: you can redistribute it and/or modify
4#   it under the terms of the GNU General Public License as published by
5#   the Free Software Foundation, either version 3 of the License, or
6#   (at your option) any later version.
7
8#   PARPG is distributed in the hope that it will be useful,
9#   but WITHOUT ANY WARRANTY; without even the implied warranty of
10#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11#   GNU General Public License for more details.
12
13#   You should have received a copy of the GNU General Public License
14#   along with PARPG.  If not, see <http://www.gnu.org/licenses/>.
15"""
16Provides classes used to serialize and deserialize Python classes.
17"""
18
19from abc import ABCMeta, abstractmethod
20try:
21    from xml.etree import cElementTree as ElementTree
22except ImportError:
23    from xml.etree import ElementTree
24try:
25    from collections import OrderedDict
26except ImportError:
27    from .common.ordereddict import OrderedDict
28
29from .common.utils import dedent_chomp
30
31class Serializable(object):
32    def __init__(self, class_, init_args=None, attributes=None):
33        self.class_ = class_
34        if init_args is not None:
35            self.init_args = OrderedDict(init_args)
36        else:
37            self.init_args = OrderedDict()
38        if attributes is not None:
39            self.attributes = OrderedDict(attributes)
40        else:
41            self.attributes = OrderedDict()
42
43
44class SerializableRegistry(object):
45    """
46    Class holding the data used to serialize and deserialize a particular
47    Python object.
48    """
49    registered_classes = {}
50   
51    @classmethod
52    def registerClass(cls, name, class_, init_args=None, attributes=None):
53        serializable = Serializable(class_, init_args, attributes)
54        cls.registered_classes[name] = serializable
55
56
57class AbstractSerializer(object):
58    __metaclass__ = ABCMeta
59   
60    @abstractmethod
61    def serialize(self, object_, stream):
62        pass
63   
64    @abstractmethod
65    def deserialize(self, stream):
66        pass
67
68
69class XmlSerializer(AbstractSerializer):
70    def serialize(self, statistic, stream):
71        pass
72   
73    @classmethod
74    def deserialize(cls, stream):
75        element_tree = ElementTree.parse(stream)
76        root_element = element_tree.getroot()
77        object_ = cls.construct_object(root_element)
78        return object_
79   
80    @classmethod
81    def construct_object(cls, element):
82        element_name = element.tag
83        if element_name in SerializableRegistry.registered_classes.keys():
84            object_ = cls.construct_registered_class(element)
85        elif len(element) > 0:
86            # Element contains subelements, so we'll treat it as an
87            # OrderedDict.
88            if element_name == 'list':
89                object_ = cls.construct_list(element)
90            else:
91                object_ = cls.construct_ordered_dict(element)
92        else:
93            object_ = cls.construct_primitive(element)
94        return object_
95   
96    @classmethod
97    def construct_registered_class(cls, element):
98        element_name = element.tag
99        serializable = SerializableRegistry.registered_classes[element_name]
100        class_ = serializable.class_
101        init_args = OrderedDict()
102        for subelement in element:
103            arg = cls.construct_object(subelement)
104            subelement_name = subelement.tag
105            init_args[subelement_name] = arg
106        try:
107            object_ = class_(**init_args)
108        except (TypeError, ValueError) as exception:
109            print(init_args)
110            error_message = \
111                'unable to deserialize tag {0}: {1}'.format(element_name,
112                                                            exception)
113            raise ValueError(error_message)
114        return object_
115   
116    @classmethod
117    def construct_ordered_dict(cls, element):
118        object_ = OrderedDict()
119        for subelement in element:
120            child = cls.construct_object(subelement)
121            name = subelement.tag
122            object_[name] = child
123        return object_
124   
125    @classmethod
126    def construct_list(cls, element):
127        object_ = []
128        for subelement in element:
129            child = cls.construct_object(subelement)
130            object_.append(child)
131        return object_
132   
133    @classmethod
134    def construct_primitive(cls, element):
135        text = element.text
136        # Interpret the element's text as unicode by default.
137        element_type = element.attrib.get('type', 'unicode')
138        if element_type == 'unicode':
139            formatted_text = dedent_chomp(text)
140            object_ = unicode(formatted_text)
141        elif element_type == 'str':
142            formatted_text = dedent_chomp(text)
143            object_ = str(formatted_text)
144        elif element_type == 'int':
145            object_ = int(text)
146        elif element_type == 'float':
147            object_ = float(text)
148        else:
149            error_message = '{0!r} is not a recognized primitive type'
150            error_message.format(element_type)
151            raise ValueError(error_message)
152        return object_
Note: See TracBrowser for help on using the repository browser.