File: serialization.py

package info (click to toggle)
python-mistral-lib 3.3.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 392 kB
  • sloc: python: 1,346; makefile: 21; sh: 2
file content (210 lines) | stat: -rw-r--r-- 6,307 bytes parent folder | download | duplicates (5)
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
#    Copyright 2017 Nokia Networks.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import abc

from oslo_serialization import jsonutils


_SERIALIZER = None


class Serializer(object):
    """Base interface for entity serializers.

    A particular serializer knows how to convert a certain object
    into a string and back from that string into an object whose
    state is equivalent to the initial object.
    """

    @abc.abstractmethod
    def serialize(self, entity):
        """Converts the given object into a string.

        :param entity: An object to be serialized.
        :return String containing the state of the object in serialized form.
        """
        raise NotImplementedError

    @abc.abstractmethod
    def deserialize(self, data_str):
        """Converts the given string into an object.

        :param data_str: String containing the state of the object in
            serialized form.
        :return: An object.
        """
        raise NotImplementedError


class DictBasedSerializer(Serializer):
    """Dictionary-based serializer.

    It slightly simplifies implementing custom serializers by introducing
    a contract based on dictionary. A serializer class extending this class
    just needs to implement conversion from object into dict and from dict
    to object. It doesn't need to convert into string and back as required
    bye the base serializer contract. Conversion into string is implemented
    once with regard to possible problems that may occur for collection and
    primitive types as circular dependencies, correct date format etc.
    """

    def serialize(self, entity):
        if entity is None:
            return None

        entity_dict = self.serialize_to_dict(entity)

        return jsonutils.dumps(
            jsonutils.to_primitive(entity_dict, convert_instances=True)
        )

    def deserialize(self, data_str):
        if data_str is None:
            return None

        entity_dict = jsonutils.loads(data_str)

        return self.deserialize_from_dict(entity_dict)

    @abc.abstractmethod
    def serialize_to_dict(self, entity):
        raise NotImplementedError

    @abc.abstractmethod
    def deserialize_from_dict(self, entity_dict):
        raise NotImplementedError


class MistralSerializable(object):
    """A mixin to generate a serialization key for a custom object."""

    @classmethod
    def get_serialization_key(cls):
        return "%s.%s" % (cls.__module__, cls.__name__)


class PolymorphicSerializer(Serializer):
    """Polymorphic serializer.

    The purpose of this class is to serve as a serialization router
    between serializers that can work with entities of particular type.
    All concrete serializers associated with concrete entity classes
    should be registered via method 'register', after that an instance
    of polymorphic serializer can be used as a universal serializer
    for an RPC system or something else.
    When converting an object into a string this serializer also writes
    a special key into the result string sequence so that it's possible
    to find a proper serializer when deserializing this object.
    If a primitive value is given as an entity this serializer doesn't
    do anything special and simply converts a value into a string using
    jsonutils. Similar when it converts a string into a primitive value.
    """

    def __init__(self):
        # {serialization key: serializer}
        self.serializers = {}

    @staticmethod
    def _get_serialization_key(entity_cls):
        if issubclass(entity_cls, MistralSerializable):
            return entity_cls.get_serialization_key()

        return None

    def register(self, entity_cls, serializer):
        key = self._get_serialization_key(entity_cls)

        if not key:
            return

        if key in self.serializers:
            raise RuntimeError(
                "A serializer for the entity class has already been"
                " registered: %s" % entity_cls
            )

        self.serializers[key] = serializer

    def unregister(self, entity_cls):
        key = self._get_serialization_key(entity_cls)

        if not key:
            return

        if key in self.serializers:
            del self.serializers[key]

    def cleanup(self):
        self.serializers.clear()

    def serialize(self, entity):
        if entity is None:
            return None

        key = self._get_serialization_key(type(entity))

        # Primitive or not registered type.
        if not key:
            return jsonutils.dumps(
                jsonutils.to_primitive(entity, convert_instances=True)
            )

        serializer = self.serializers.get(key)

        if not serializer:
            raise RuntimeError(
                "Failed to find a serializer for the key: %s" % key
            )

        result = {
            '__serial_key': key,
            '__serial_data': serializer.serialize(entity)
        }

        return jsonutils.dumps(result)

    def deserialize(self, data_str):
        if data_str is None:
            return None

        data = jsonutils.loads(data_str)

        if isinstance(data, dict) and '__serial_key' in data:
            serializer = self.serializers.get(data['__serial_key'])

            return serializer.deserialize(data['__serial_data'])

        return data


def get_polymorphic_serializer():
    global _SERIALIZER

    if _SERIALIZER is None:
        _SERIALIZER = PolymorphicSerializer()

    return _SERIALIZER


def register_serializer(entity_cls, serializer):
    get_polymorphic_serializer().register(entity_cls, serializer)


def unregister_serializer(entity_cls):
    get_polymorphic_serializer().unregister(entity_cls)


def cleanup():
    get_polymorphic_serializer().cleanup()