Beispiel #1
0
    def dataclass_definition(self) -> DataclassDefinition:
        # Determine the dataclass that we should operate on.
        if self.dataclass:
            assert not hasattr(self, 'Meta'), (
                "Class '{serializer_class}' may not have `Meta` attribute when instantiated with `dataclass` parameter."
                .format(serializer_class=self.__class__.__name__))

            dataclass_type = self.dataclass
        else:
            assert hasattr(self, 'Meta'), (
                "Class '{serializer_class}' missing `Meta` attribute.".format(
                    serializer_class=self.__class__.__name__))

            meta = getattr(self, 'Meta')
            assert hasattr(meta, 'dataclass'), (
                "Class '{serializer_class}' missing `Meta.dataclass` attribute."
                .format(serializer_class=self.__class__.__name__))

            dataclass_type = meta.dataclass

        # Make sure we're dealing with an actual dataclass.
        if not dataclasses.is_dataclass(dataclass_type):
            raise ValueError(
                "Class '{serializer_class}' can only be used to serialize dataclasses."
                .format(serializer_class=self.__class__.__name__))

        return get_dataclass_definition(dataclass_type)
    def get_fields(self) -> Dict[str, SerializerField]:
        """
        Return the dict of field names -> field instances that should be used for `self.fields` when instantiating the
        serializer.
        """
        # Make sure we're dealing with an actual dataclass.
        dataclass_type = self.get_dataclass_type()
        if not dataclasses.is_dataclass(dataclass_type):
            raise ValueError(
                "Class '{serializer_class}' can only be used to serialize dataclasses."
                .format(serializer_class=self.__class__.__name__))

        declared_fields = copy.deepcopy(self._declared_fields)

        # Retrieve metadata about fields on the dataclass.
        definition = get_dataclass_definition(dataclass_type)
        field_names = self.get_field_names(declared_fields, definition)

        # Determine any extra field arguments that should be included.
        extra_kwargs = self.get_extra_kwargs()

        # Determine the fields that should be included on the serializer.
        fields = OrderedDict()

        for field_name in field_names:
            # If the field is explicitly declared on the class then use that.
            if field_name in declared_fields:
                fields[field_name] = declared_fields[field_name]
                continue

            extra_field_kwargs = extra_kwargs.get(field_name, {})
            fields[field_name] = self.create_field(definition, field_name,
                                                   extra_field_kwargs)

        return fields