From 724dd2043ec849e605ba4f4cf1430458c2a8d90a Mon Sep 17 00:00:00 2001 From: Berker Peksag Date: Wed, 8 Jun 2016 04:22:30 +0300 Subject: [PATCH] Fixed #26717 -- Added Serializer.stream_class to customize the stream. --- django/core/serializers/base.py | 3 ++- docs/releases/1.11.txt | 3 ++- tests/serializers/tests.py | 23 +++++++++++++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/django/core/serializers/base.py b/django/core/serializers/base.py index 7cf66b15f7a..a6c88472789 100644 --- a/django/core/serializers/base.py +++ b/django/core/serializers/base.py @@ -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) diff --git a/docs/releases/1.11.txt b/docs/releases/1.11.txt index 1436ffe9649..c94935f93ae 100644 --- a/docs/releases/1.11.txt +++ b/docs/releases/1.11.txt @@ -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 ~~~~~~~ diff --git a/tests/serializers/tests.py b/tests/serializers/tests.py index 96284ca6429..66f1d223985 100644 --- a/tests/serializers/tests.py +++ b/tests/serializers/tests.py @@ -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']