Return serialized queryset or single object as python dictionary
        serialize() only works on iterables, so to serialize a single object we put it in a list
13728
def serialize_queryset(self, queryset):
        
        object_data = []
        is_queryset = False
        query_fields = self.get_fields()
        try:
            iter(queryset)
            is_queryset = True
            raw_data = serializers.serialize(self.serializer_name, queryset, fields=query_fields,
                                             use_natural_keys=self.serialize_natural_keys)
        except TypeError:  # Not iterable
            raw_data = serializers.serialize(self.serializer_name, [queryset, ], fields=query_fields,
                                             use_natural_keys=self.serialize_natural_keys)

        for obj in raw_data:  # Add pk to fields
            obj['fields']['pk'] = obj['pk']
            object_data.append(obj['fields'])

        if is_queryset:
            return object_data
        return object_data[0]
396977
def serialize(self):
        

        def _serialize(value):
            if hasattr(value, 'serialize'):
                return value.serialize()
            elif hasattr(value, 'to_dict'):
                return value.to_dict()
            else:
                return value

        return list(map(_serialize, self.items))
1271837
def get_object_or_none(klass, *args, **kwargs):
    
    queryset = _get_queryset(klass)
    try:
        return queryset.get(*args, **kwargs)
    except:  # noqa: E722
        return None
581051
def get_object(self, queryset=None):
        
        # Determine the base queryset to use.
        assert queryset is None, "Passing a queryset is disabled"
        queryset = self.filter_queryset(self.get_queryset())

        # Perform the lookup filtering.
        lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
        lookup = self.kwargs.get(lookup_url_kwarg, None)
        assert lookup is not None, "Other lookup methods are disabled"
        filter_kwargs = {self.lookup_field: lookup}
        obj = self.get_object_or_404(queryset, **filter_kwargs)

        # May raise a permission denied
        self.check_object_permissions(self.request, obj)

        return obj
593463
def to_serializable_value(self):
        
        return_dict = {}
        for name, field in self.__dict__.items():
            if isinstance(field, fields.Field):
                return_dict[name] = field.to_serializable_value()
        return return_dict
551759
def _serialize_object(self, response_data, request):
        
        if self._is_doc_request(request):
            return response_data
        else:
            return super(DocumentedResource, self)._serialize_object(
                response_data, request)
105250
def serialize(d):
    
    ret = {}
    for k,v in d.items():
        if not k.startswith('_'):
            ret[k] = str(d[k])
    #ret['__class__'] = obj.__class__.__name__
    return ret
429515
def make_serializable(data):
    """"""
    if is_serializable(data):
        return data

    # if numpy array convert to list
    try:
        return data.tolist()
    except AttributeError:
        pass
    except Exception as e:
        logger.debug('{} exception ({}): {}'.format(type(e).__name__, e, data))

    # try serializing each child element
    if isinstance(data, dict):
        return {key: make_serializable(value) for key, value in data.items()}
    try:
        return [make_serializable(element) for element in data]
    except TypeError:  # not iterable
        pass
    except Exception:
        logger.debug('Could not serialize {}; converting to string'.format(data))

    # last resort: convert to string
    return str(data)
748721
def serialize(obj):
        
        if isinstance(obj, str_types):
            return obj
        elif hasattr(obj, 'timetuple'):
            return int(time.mktime(obj.timetuple())) * 1000
        elif hasattr(obj, 'item'):
            return obj.item()
        elif hasattr(obj, '__float__'):
            if isinstance(obj, int):
                return int(obj)
            else:
                return float(obj)
        elif hasattr(obj, '__int__'):
            return int(obj)
        else:
            raise LoadError('cannot serialize index of type '
                            + type(obj).__name__)
959395
def get(self, request, *args, **kwargs):
        
        # init django rest framework specific stuff
        serializer_class = self.get_serializer_class()
        context = self.get_serializer_context()

        # init empty list
        services = []

        # loop over each service
        for service_type in SERVICES.keys():
            # initialize serializers for layer
            services.append(
                serializer_class(
                    object(),
                    context=context,
                    service_type=service_type
                ).data
            )

        return Response(services)
1358387
def serialize_hook(instance):
    

    if getattr(instance, 'serialize_hook', None) and callable(instance.serialize_hook):
        return instance.serialize_hook(hook=instance)
    if getattr(settings, 'HOOK_SERIALIZER', None):
        serializer = get_module(settings.HOOK_SERIALIZER)
        return serializer(instance, hook=instance)
    # if no user defined serializers, fallback to the django builtin!
    return {
        'hook': instance.dict(),
        'data': serializers.serialize('python', [instance])[0]
    }
220882
def to_single_data(input):
    
    if (isinstance(input, (list, tuple)) and len(input) == 1):
        return input[0]
    else:
        assert isinstance(input, dict), input
        return input
1011304
def from_serializable(cls, object_dict):
        

        key_class = cls._from_visible(cls.STARTS_WITH + 'class' + cls.ENDS_WITH)
        key_module = cls._from_visible(cls.STARTS_WITH + 'module' + cls.ENDS_WITH)

        obj_class = object_dict.pop(key_class)
        obj_module = object_dict.pop(key_module) if key_module in object_dict else None

        obj = cls._from_class(obj_class, obj_module)
        obj.modify_object(object_dict)
        return obj
390044
def _serialize_default(cls, obj):
        

        if obj is None or cls._is_primitive(obj):
            return obj
        elif cls._is_bytes(obj):
            return obj.decode()
        elif type(obj) == list:
            return cls._serialize_list(obj)
        else:
            dict_ = cls._get_obj_raw(obj)

            return cls._serialize_dict(dict_)
643954
def serialize(self, data):
        
        if data is None:
            return None
        elif isinstance(data, dict):
            return serializer.Serializer().serialize(data)
        else:
            raise Exception(_("Unable to serialize object of type = '%s'") %
                            type(data))
567301
def get_object(self, queryset=None):
        
        try:
            obj = self.get_queryset()
        except self.model.DoesNotExist:
            raise Http404()
        self.check_object_permissions(self.request, obj)
        return obj
998140
def deserialize(self, to_deserialize: PrimitiveJsonType) \
            -> Optional[Union[SerializableType, List[SerializableType]]]:
        
        if to_deserialize is None:
            # Implements #17
            return None
        elif isinstance(to_deserialize, List):
            deserialized = []
            for item in to_deserialize:
                item_deserialized = self.deserialize(item)
                deserialized.append(item_deserialized)
            return deserialized
        else:
            mappings_not_set_in_constructor = []    # type: List[PropertyMapping]

            init_kwargs = dict()    # type: Dict[str, Any]
            for mapping in self._property_mappings:
                if mapping.object_constructor_parameter_name is not None:
                    value = mapping.serialized_property_getter(to_deserialize)
                    if not (mapping.optional and value is None):
                        decoded_value = self._deserialize_property_value(value, mapping.deserializer_cls)
                        if isinstance(decoded_value, list):
                            collection = mapping.collection_factory(decoded_value)
                            decoded_value = collection

                        argument = mapping.object_constructor_argument_modifier(decoded_value)
                        init_kwargs[mapping.object_constructor_parameter_name] = argument
                else:
                    mappings_not_set_in_constructor.append(mapping)

            decoded = self._deserializable_cls(**init_kwargs)
            assert type(decoded) == self._deserializable_cls

            for mapping in mappings_not_set_in_constructor:
                assert mapping.object_constructor_parameter_name is None
                if mapping.serialized_property_getter is not None and mapping.object_property_setter is not None:
                    value = mapping.serialized_property_getter(to_deserialize)
                    if not (mapping.optional and value is None):
                        decoded_value = self._deserialize_property_value(value, mapping.deserializer_cls)
                        if isinstance(decoded_value, list):
                            collection = mapping.collection_factory(decoded_value)
                            decoded_value = collection

                        mapping.object_property_setter(decoded, decoded_value)

            return decoded