From 14449a4bd7f834b60e577a0167413a9adc6e8d09 Mon Sep 17 00:00:00 2001 From: Clark DuVall Date: Thu, 10 Sep 2015 20:51:41 -0700 Subject: [PATCH] Django REST Framework compatibility --- serpy/serializer.py | 29 +++++++++++++++++------------ tests/test_serializer.py | 3 +++ 2 files changed, 20 insertions(+), 12 deletions(-) diff --git a/serpy/serializer.py b/serpy/serializer.py index f2b63af..4945e1d 100644 --- a/serpy/serializer.py +++ b/serpy/serializer.py @@ -77,26 +77,31 @@ class FooSerializer(Serializer): FooSerializer(foo).data # {'foo': 'hello', 'bar': 5} - :param obj: The object or objects to serialize. - :param bool many: If ``obj`` is a collection of objects, set ``many`` to - ``True`` to serialize to a list. + :param instance: The object or objects to serialize. + :param bool many: If ``instance`` is a collection of objects, set ``many`` + to ``True`` to serialize to a list. """ #: The default getter used if :meth:`Field.as_getter` returns None. default_getter = operator.attrgetter - def __init__(self, obj=None, many=False, **kwargs): + def __init__(self, instance=None, many=False, data=None, context=None, + **kwargs): + if data is not None: + raise RuntimeError( + 'serpy serializers do not support input validation') + super(Serializer, self).__init__(**kwargs) - self.obj = obj + self.instance = instance self.many = many self._data = None - def _serialize(self, obj, fields): + def _serialize(self, instance, fields): v = {} for name, getter, to_value, call, required, pass_self in fields: if pass_self: - result = getter(self, obj) + result = getter(self, instance) else: - result = getter(obj) + result = getter(instance) if required or result is not None: if call: result = result() @@ -106,12 +111,12 @@ def _serialize(self, obj, fields): return v - def to_value(self, obj): + def to_value(self, instance): fields = self._compiled_fields if self.many: serialize = self._serialize - return [serialize(o, fields) for o in obj] - return self._serialize(obj, fields) + return [serialize(o, fields) for o in instance] + return self._serialize(instance, fields) @property def data(self): @@ -121,7 +126,7 @@ def data(self): """ # Cache the data for next time .data is called. if self._data is None: - self._data = self.to_value(self.obj) + self._data = self.to_value(self.instance) return self._data diff --git a/tests/test_serializer.py b/tests/test_serializer.py index 384ab94..1ef9b05 100644 --- a/tests/test_serializer.py +++ b/tests/test_serializer.py @@ -170,6 +170,9 @@ class ASerializer(Serializer): o = Obj(a=None) self.assertRaises(TypeError, lambda: ASerializer(o).data) + def test_error_on_data(self): + self.assertRaises(RuntimeError, lambda: Serializer(data='foo')) + if __name__ == '__main__': unittest.main()