Make ReturnDict cachable. Closes #2360.

This commit is contained in:
Tom Christie 2015-01-21 14:18:13 +00:00
parent 9d24809a4d
commit e59b3d1718
2 changed files with 27 additions and 0 deletions

View File

@ -19,6 +19,11 @@ class ReturnDict(OrderedDict):
def __repr__(self):
return dict.__repr__(self)
def __reduce__(self):
# Pickling these objects will drop the .serializer backlink,
# but preserve the raw data.
return (dict, (dict(self),))
class ReturnList(list):
"""
@ -33,6 +38,11 @@ class ReturnList(list):
def __repr__(self):
return list.__repr__(self)
def __reduce__(self):
# Pickling these objects will drop the .serializer backlink,
# but preserve the raw data.
return (list, (list(self),))
class BoundField(object):
"""

View File

@ -3,6 +3,7 @@ from __future__ import unicode_literals
from .utils import MockObject
from rest_framework import serializers
from rest_framework.compat import unicode_repr
import pickle
import pytest
@ -278,3 +279,19 @@ class TestNotRequiredOutput:
serializer = ExampleSerializer(instance)
with pytest.raises(AttributeError):
serializer.data
class TestCacheSerializerData:
def test_cache_serializer_data(self):
"""
Caching serializer data with pickle will drop the serializer info,
but does preserve the data itself.
"""
class ExampleSerializer(serializers.Serializer):
field1 = serializers.CharField()
field2 = serializers.CharField()
serializer = ExampleSerializer({'field1': 'a', 'field2': 'b'})
pickled = pickle.dumps(serializer.data)
data = pickle.loads(pickled)
assert data == {'field1': 'a', 'field2': 'b'}