From 0594fed9ffd6cf6e10475488934cb02d9263829e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Langa?= Date: Tue, 21 May 2013 00:41:23 +0200 Subject: [PATCH] Fixed #20472: response.content should be bytes on both Python 2 and 3 --- django/http/utils.py | 4 ++-- tests/http_utils/tests.py | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/django/http/utils.py b/django/http/utils.py index fcb3fecb6c..e13dc4cbb6 100644 --- a/django/http/utils.py +++ b/django/http/utils.py @@ -31,13 +31,13 @@ def conditional_content_removal(request, response): if response.streaming: response.streaming_content = [] else: - response.content = '' + response.content = b'' response['Content-Length'] = '0' if request.method == 'HEAD': if response.streaming: response.streaming_content = [] else: - response.content = '' + response.content = b'' return response diff --git a/tests/http_utils/tests.py b/tests/http_utils/tests.py index 7dfd24d721..06a310a787 100644 --- a/tests/http_utils/tests.py +++ b/tests/http_utils/tests.py @@ -1,10 +1,21 @@ from __future__ import unicode_literals +import io +import gzip + from django.http import HttpRequest, HttpResponse, StreamingHttpResponse from django.http.utils import conditional_content_removal from django.test import TestCase +# based on Python 3.3's gzip.compress +def gzip_compress(data): + buf = io.BytesIO() + with gzip.GzipFile(fileobj=buf, mode='wb', compresslevel=0) as f: + f.write(data) + return buf.getvalue() + + class HttpUtilTests(TestCase): def test_conditional_content_removal(self): @@ -33,6 +44,19 @@ class HttpUtilTests(TestCase): conditional_content_removal(req, res) self.assertEqual(b''.join(res), b'') + # Issue #20472 + abc = gzip_compress(b'abc') + res = HttpResponse(abc, status=304) + res['Content-Encoding'] = 'gzip' + conditional_content_removal(req, res) + self.assertEqual(res.content, b'') + + res = StreamingHttpResponse([abc], status=304) + res['Content-Encoding'] = 'gzip' + conditional_content_removal(req, res) + self.assertEqual(b''.join(res), b'') + + # Strip content for HEAD requests. req.method = 'HEAD'