Fixed #26717 -- Added Serializer.stream_class to customize the stream.
This commit is contained in:
parent
7767978bee
commit
724dd2043e
|
@ -59,6 +59,7 @@ class Serializer(object):
|
|||
# internal Django use.
|
||||
internal_use_only = False
|
||||
progress_class = ProgressBar
|
||||
stream_class = six.StringIO
|
||||
|
||||
def serialize(self, queryset, **options):
|
||||
"""
|
||||
|
@ -66,7 +67,7 @@ class Serializer(object):
|
|||
"""
|
||||
self.options = options
|
||||
|
||||
self.stream = options.pop("stream", six.StringIO())
|
||||
self.stream = options.pop("stream", self.stream_class())
|
||||
self.selected_fields = options.pop("fields", None)
|
||||
self.use_natural_foreign_keys = options.pop('use_natural_foreign_keys', False)
|
||||
self.use_natural_primary_keys = options.pop('use_natural_primary_keys', False)
|
||||
|
|
|
@ -192,7 +192,8 @@ Requests and Responses
|
|||
Serialization
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
* ...
|
||||
* The new ``django.core.serializers.base.Serializer.stream_class`` attribute
|
||||
allows subclasses to customize the default stream.
|
||||
|
||||
Signals
|
||||
~~~~~~~
|
||||
|
|
|
@ -353,6 +353,29 @@ class SerializersTestBase(object):
|
|||
self.assertEqual(base_data, proxy_proxy_data.replace('proxy', ''))
|
||||
|
||||
|
||||
class SerializerAPITests(SimpleTestCase):
|
||||
|
||||
def test_stream_class(self):
|
||||
class File(object):
|
||||
def __init__(self):
|
||||
self.lines = []
|
||||
|
||||
def write(self, line):
|
||||
self.lines.append(line)
|
||||
|
||||
def getvalue(self):
|
||||
return ''.join(self.lines)
|
||||
|
||||
class Serializer(serializers.json.Serializer):
|
||||
stream_class = File
|
||||
|
||||
serializer = Serializer()
|
||||
data = serializer.serialize([Score(id=1, score=3.4)])
|
||||
self.assertIs(serializer.stream_class, File)
|
||||
self.assertIsInstance(serializer.stream, File)
|
||||
self.assertEqual(data, '[{"model": "serializers.score", "pk": 1, "fields": {"score": 3.4}}]')
|
||||
|
||||
|
||||
class SerializersTransactionTestBase(object):
|
||||
|
||||
available_apps = ['serializers']
|
||||
|
|
Loading…
Reference in New Issue