Example #1
0
    def serialize(self, obj: Any) -> Any:
        if not hasattr(obj, '__getitem__'):
            raise SerializationError(val=obj, reason='invalid_obj', origin=self)

        try:
            r = obj[self.name]
        except KeyError as e:
            raise SerializationError(val=obj, reason='key_missing', exc=e, origin=self)

        with subserializer('$item'):
            return self.dependencies['type'].serialize(r)
Example #2
0
    def serialize(self, obj: Any) -> Any:
        if isinstance(obj, dict):
            r = {}
            for k, v in obj.items():
                with subserializer('$key'):
                    k = self.serialize(k)
                assert isinstance(k, str), k

                with subserializer('$value'):
                    v = self.serialize(v)

                r[k] = v
            return r
        elif isinstance(obj, list):
            r = []

            for i, v in enumerate(obj):
                with subserializer(i):
                    r.append(self.serialize(v))
            return r
        elif isinstance(obj, str):
            return obj
        elif isinstance(obj, float):
            return obj
        elif isinstance(obj, int):
            return obj
        elif obj is None:
            return obj
        else:
            raise SerializationError(val=obj, reason='not_json_value')
Example #3
0
    def serialize(self, obj: Any) -> Any:
        with subserializer('$body'):
            val = self.dependencies['body'].serialize(obj)

        try:
            return json.loads(bytes(val))
        except Exception as e:
            raise SerializationError(val=obj, reason='json', exc=e, origin=self)
Example #4
0
    def serialize(self, obj: Tuple[int, bytes]) -> BinaryNext:
        with subserializer('$size'):
            size = self.dependencies['size'].serialize(obj)

        with subserializer('$body'):
            body = self.dependencies['body'].serialize(obj)

        if not isinstance(size, int):
            raise SerializationError(val=obj, reason='not_int', origin=self)

        if not isinstance(body, bytes) and not isinstance(body, memoryview):
            raise SerializationError(val=obj, reason='not_bytes', origin=self)

        if len(body) < size:
            raise SerializationError(val=obj, reason=BUFFER_NEEDED, origin=self)

        return BinaryNext(body[:size], body[size:])
Example #5
0
    def serialize(self, obj: Any) -> Any:
        with subserializer('$value'):
            obj2 = self.dependencies['value'].serialize(obj)

        if obj2 not in self.lookup:
            raise SerializationError(val=obj, exc=KeyError(obj2), reason='key_missing')

        return self.lookup[obj2]
Example #6
0
    def serialize(self, obj: Any) -> Any:
        if self.type is not None:
            try:
                obj = self.type(obj)
            except Exception as e:
                raise SerializationError(val=obj, exc=e, reason='unmappable', origin=self)

        return obj
Example #7
0
    def serialize(self, obj: 'Frame') -> bytes:
        try:
            body = json.dumps(obj.body).encode('utf-8')
        except Exception as e:
            raise SerializationError(val=obj, reason=f'json:{e}')

        size = self.dependencies['varint'].serialize(len(body))

        return size + body
Example #8
0
    def serialize(self, obj: Any) -> Any:
        with subserializer('value'):
            obj = self.dependencies['value'].serialize(obj)

        if not isinstance(obj, self.enum):
            raise SerializationError(val=obj,
                                     reason='enum_not_enum',
                                     origin=self)

        try:
            obj = obj.value
        except AttributeError as e:
            raise SerializationError(val=obj,
                                     exc=e,
                                     reason='invalid_enum',
                                     origin=self)

        return obj
Example #9
0
    def serialize(self, obj: bytes) -> Tuple['Frame', bytes]:
        size, obj = self.dependencies['varint'].serialize(obj)
        body, obj = self.dependencies['bytes'].serialize((size, obj))

        try:
            body = json.loads(body)
        except json.JSONDecodeError as e:
            raise SerializationError(val=body, reason=f'json:{e}')

        return Frame(body), obj
Example #10
0
    def serialize(self, obj: Any) -> Any:
        if self.cls and not isinstance(obj, self.cls):
            raise SerializationError(val=obj,
                                     reason='not_instance',
                                     origin=self)

        r = OrderedDict()

        for idx, v in self.dependencies.items():
            with subserializer(idx):
                item = v.serialize(obj)

                if not isinstance(item, FieldValue):
                    raise SerializationError(val=item,
                                             reason='unsupported_field_defn',
                                             origin=self)

            if item.has_value:
                r[item.name] = item.value
        return r
Example #11
0
    def serialize(self, obj: Any) -> Any:
        try:
            r = getattr(obj, self.name)
        except AttributeError as e:
            raise SerializationError(val=obj, reason=f'attr_missing', origin=self, exc=e)

        if len(self.dependencies):
            with subserializer('$attr'):
                return self.dependencies['type'].serialize(r)
        else:
            return r
Example #12
0
    def serialize(self, obj: Any) -> Any:
        with subserializer('$value'):
            obj2 = self.dependencies['value'].serialize(obj)

        try:
            return self.enum(obj2)
        except Exception as e:
            raise SerializationError(path=['$enum'],
                                     val=obj,
                                     exc=e,
                                     reason=f'invalid_enum_key',
                                     origin=self)
Example #13
0
    def serialize(self, obj: bytes) -> BinaryNext:
        if not isinstance(obj, bytes) and not isinstance(obj, memoryview):
            raise SerializationError(val=obj, reason='not_bytes', origin=self)

        r = 0
        i = 0
        curr = memoryview(obj)

        while True:
            if len(curr) == 0:
                raise SerializationError(val=obj, reason=BUFFER_NEEDED, origin=self)

            item, curr = curr[0], curr[1:]

            r = r | ((item & 127) << (7 * i))

            i += 1

            if item & 128 == 0:
                break

        return BinaryNext(r, curr)
Example #14
0
    def serialize(self, obj: Any) -> Any:
        with subserializer('$discriminant'):
            discriminant = self.dependencies['discriminant'].serialize(obj)

        if discriminant not in self.items:
            raise SerializationError(val=obj, path=['$value'], origin=self,
                                     reason=f'`{discriminant}` is not in the map')

        with subserializer('$value'):
            value = self.dependencies['value'].serialize(obj)

        depk = self.items[discriminant]
        dep = self.dependencies[depk]

        with subserializer('$sub'):
            return dep.serialize(value)
Example #15
0
    def serialize(self, obj: Any) -> Any:
        r = {}
        for idx, v in self.dependencies.items():
            with subserializer(idx):
                item = v.serialize(obj)

                if not isinstance(item, FieldValue):
                    raise SerializationError(val=item,
                                             reason='unsupported_field_defn',
                                             origin=self)

            if item.has_value:
                r[item.name] = item.value

        if self.cls:
            return self.cls(**r)
        else:
            return r
Example #16
0
    def serialize(self, obj: Any) -> Any:
        if not isinstance(obj, int):
            raise SerializationError(val=obj, reason='not_int', origin=self)

        r = []

        while True:

            next_obj = obj >> 7

            if next_obj == 0:
                r.append(obj)
                break
            else:
                r.append(obj & 127 | 128)
                obj = next_obj

        return bytes(r)
Example #17
0
 def serialize(self, obj: float) -> timedelta:
     try:
         obj = float(obj)
     except Exception as e:
         raise SerializationError(val=obj, reason=str(e))
     return timedelta(seconds=obj)
Example #18
0
    def serialize(self, obj: datetime) -> Any:
        if not isinstance(obj, datetime):
            raise SerializationError(val=obj)

        return format(obj, self.format)
Example #19
0
 def serialize(self, obj: Any) -> Any:
     try:
         r = datetime.strptime(obj, self.format)
     except Exception as e:
         raise SerializationError(val=obj, reason=str(e))
     return r.replace(tzinfo=pytz.utc)
Example #20
0
    def serialize(self, obj: timedelta) -> Any:
        if not isinstance(obj, timedelta):
            raise SerializationError(val=obj)

        return obj.total_seconds()