示例#1
0
 def to_python(self, value: object) -> object:
     """Returns the python version of the supplied value. By default, it's
     the same as the value supplied, but this can be overridden by fields
     to provide a conversion to a different datatype
     """
     logger.debug(f"{repr(self)}: serializing to python: {repr(value)}")
     return value
示例#2
0
    def to_api(self, value: type) -> str:
        logger.debug(f"{repr(self)}: deserializing to api: {repr(value)}")
        value = self.clean(value)

        if value is None:
            return None

        return value.isoformat()
示例#3
0
    def to_api(self, value: Union[ResourceCollection, _TypeCollection]):
        """Transforms the collection into a list, and chains the call to it's
        children.
        """
        logger.debug(f"{repr(self)}: deserializing to api: {repr(value)}")

        if value is None or value in self.empty_values:
            return []

        return value.to_api()
示例#4
0
    def to_python(self, value: list):
        """Creates a collection object from the supplied list"""
        cls = self.collection
        logger.debug(f"{repr(self)}: serializing to python: {repr(value)}")

        if isinstance(cls, str):
            app_label = self.resource._meta.app_label

            if len(cls.split('.')) == 2:
                app_label, cls = cls.split('.')

            cls = registry.get_collection(app_label, cls)

        return cls(value)
示例#5
0
    def to_api(self, value: Resource):
        """Transforms the resources into a dict, and chains the call to it's
        children.
        """
        logger.debug(f"{repr(self)}: deserializing to api: {repr(value)}")

        if value is None or value in self.empty_values:
            if not self.null or not self.blank:
                raise ValueError('Cannot serialize null, as it\'s not allowed!')
            return None

        if isinstance(value, int):
            return value

        return value.to_api()
示例#6
0
 def to_api(self, value: object) -> basic_type:
     """Cleans and validates values before casting them to the right
     API type
     """
     logger.debug(f"{repr(self)}: deserializing to api: {repr(value)}")
     if value is None:
         return value
     try:
         value = self.clean(value)
         return self.basic_type(value)
     except (TypeError, ValueError):
         raise exceptions.ValidationError(
             self.error_messages['invalid'],
             code='invalid',
             params={
                 'value': value
             },
         )
示例#7
0
    def to_python(self, value: dict):
        """Creates a resources object from the supplied dict"""
        cls = self.resource_class
        logger.debug(f"{repr(self)}: serializing to python: {repr(value)}")

        if value is None:
            if not self.null or not self.blank:
                raise ValueError("Tried to serialize null, but it's not "
                                 "allowed")
            return value

        if isinstance(cls, str):
            app_label = self.resource._meta.app_label

            if len(cls.split('.')) == 2:
                app_label, cls = cls.split('.')
            cls = registry.get_resource(app_label, cls)

        if isinstance(value, int):
            return value

        return cls(**value)
示例#8
0
    def to_python(self, value: str) -> type:
        logger.debug(f"{repr(self)}: serializing to python: {repr(value)}")
        if value is None:
            return value

        if isinstance(value, self.type):
            return value

        try:
            # Fix the fact that datetime.fromisoformat doesn't adhere to iso
            # 8601 properly when 'Z(ulu)' is used instead of '+00:00'
            if value[-1] == 'Z':
                value = "{}+00:00".format(value[:-1])

            return self.type.fromisoformat(value)
        except (TypeError, ValueError) as e:
            raise exceptions.ValidationError(
                "Some error!",
                code='invalid',
                params={
                    'value': value
                },
            )
示例#9
0
 def clean(self, value: object) -> object:
     """
     Convert the value's type and run validation. Validation errors
     from to_python() and validate() are propagated. Return the correct
     value if no error is raised.
     """
     logger.debug(f"{repr(self)}: Cleaning {repr(value)}")
     value = self.to_python(value)
     logger.debug(f"{repr(self)}: Resolved to {repr(value)}")
     self.validate(value)
     self.run_validators(value)
     logger.debug(f"{repr(self)}: Validated value")
     return value
示例#10
0
 def to_api(self, value: object) -> object:
     """This method should return a python datatype that can be deserialized
     properly primarily by the json module.
     """
     logger.debug(f"{repr(self)}: deserializing to api: {repr(value)}")
     pass