Skip to content

Commit

Permalink
Make ReturnDict cachable. Closes #2360.
Browse files Browse the repository at this point in the history
  • Loading branch information
tomchristie committed Jan 21, 2015
1 parent 9d24809 commit e59b3d1
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
10 changes: 10 additions & 0 deletions rest_framework/utils/serializer_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ def copy(self):
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):
"""
Expand All @@ -33,6 +38,11 @@ def __init__(self, *args, **kwargs):
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):
"""
Expand Down
17 changes: 17 additions & 0 deletions tests/test_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from .utils import MockObject
from rest_framework import serializers
from rest_framework.compat import unicode_repr
import pickle
import pytest


Expand Down Expand Up @@ -278,3 +279,19 @@ class ExampleSerializer(serializers.Serializer):
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'}

0 comments on commit e59b3d1

Please sign in to comment.