How to use the mashumaro.types.SerializationStrategy function in mashumaro

To help you get started, we’ve selected a few mashumaro examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Fatal1ty / mashumaro / mashumaro / types.py View on Github external
    @abstractmethod
    def _deserialize(cls, value):
        raise NotImplementedError


class SerializationStrategy(ABC):
    @abstractmethod
    def _serialize(self, value):
        raise NotImplementedError

    @abstractmethod
    def _deserialize(self, value):
        raise NotImplementedError


class RoundedDecimal(SerializationStrategy):
    def __init__(self, places=None, rounding=None):
        if places is not None:
            self.exp = decimal.Decimal((0, (1,), -places))
        else:
            self.exp = None
        self.rounding = rounding

    def _serialize(self, value) -> str:
        if self.exp:
            if self.rounding:
                return str(value.quantize(self.exp, rounding=self.rounding))
            else:
                return str(value.quantize(self.exp))
        else:
            return str(value)
github Fatal1ty / mashumaro / mashumaro / serializer / base / metaprogramming.py View on Github external
with self.indent():
            self.add_line('try:')
            with self.indent():
                self.add_line("kwargs = {}")
                for fname, ftype in self.fields.items():
                    self._add_type_modules(ftype)
                    self.add_line(f"value = d.get('{fname}', MISSING)")
                    self.add_line("if value is None:")
                    with self.indent():
                        self.add_line(f"kwargs['{fname}'] = None")
                    self.add_line("else:")
                    with self.indent():
                        if self.defaults[fname] is MISSING:
                            self.add_line(f"if value is MISSING:")
                            with self.indent():
                                if isinstance(ftype, SerializationStrategy):
                                    self.add_line(
                                        f"raise MissingField('{fname}',"
                                        f"{type_name(ftype.__class__)},cls)")
                                else:
                                    self.add_line(
                                        f"raise MissingField('{fname}',"
                                        f"{type_name(ftype)},cls)")
                            self.add_line("else:")
                            with self.indent():
                                unpacked_value = self._unpack_field_value(
                                    fname, ftype, self.cls)
                                self.add_line(
                                    f"kwargs['{fname}'] = {unpacked_value}")
                        else:
                            self.add_line("if value is not MISSING:")
                            with self.indent():
github Fatal1ty / mashumaro / mashumaro / serializer / base / metaprogramming.py View on Github external
def _pack_value(self, fname, ftype, parent, value_name='value'):

        if is_dataclass(ftype):
            return f"{value_name}.to_dict(use_bytes, use_enum, use_datetime)"

        with suppress(TypeError):
            if issubclass(ftype, SerializableType):
                return f'{value_name}._serialize()'
        if isinstance(ftype, SerializationStrategy):
            return f"self.__dataclass_fields__['{fname}'].type" \
                f"._serialize({value_name})"

        origin_type = get_type_origin(ftype)
        if is_special_typing_primitive(origin_type):
            if origin_type is typing.Any:
                return value_name
            elif is_union(ftype):
                args = getattr(ftype, '__args__', ())
                if len(args) == 2 and args[1] == NoneType:  # it is Optional
                    return self._pack_value(fname, args[0], parent)
                else:
                    raise UnserializableDataError(
                        'Unions are not supported by mashumaro')
            elif origin_type is typing.AnyStr:
                raise UnserializableDataError(