Fixed #25254 -- Added JsonResponse json_dumps_params parameter.

This commit is contained in:
Sambhav Satija 2015-08-12 06:23:26 +05:30 committed by Tim Graham
parent 290145e661
commit d0bd533043
4 changed files with 22 additions and 3 deletions

View File

@ -492,12 +492,16 @@ class JsonResponse(HttpResponse):
``django.core.serializers.json.DjangoJSONEncoder``.
:param safe: Controls if only ``dict`` objects may be serialized. Defaults
to ``True``.
:param json_dumps_params: A dictionary of kwargs passed to json.dumps().
"""
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True, **kwargs):
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
json_dumps_params=None, **kwargs):
if safe and not isinstance(data, dict):
raise TypeError('In order to allow non-dict objects to be '
'serialized set the safe parameter to False')
if json_dumps_params is None:
json_dumps_params = {}
kwargs.setdefault('content_type', 'application/json')
data = json.dumps(data, cls=encoder)
data = json.dumps(data, cls=encoder, **json_dumps_params)
super(JsonResponse, self).__init__(content=data, **kwargs)

View File

@ -912,7 +912,7 @@ types of HTTP responses. Like ``HttpResponse``, these subclasses live in
JsonResponse objects
====================
.. class:: JsonResponse(data, encoder=DjangoJSONEncoder, safe=True, **kwargs)
.. class:: JsonResponse(data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs)
An :class:`HttpResponse` subclass that helps to create a JSON-encoded
response. It inherits most behavior from its superclass with a couple
@ -934,6 +934,13 @@ JsonResponse objects
``dict`` instances are allowed). If ``safe`` is ``True`` and a non-``dict``
object is passed as the first argument, a :exc:`TypeError` will be raised.
The ``json_dumps_params`` parameter is a dictionary of keyword arguments
to pass to the ``json.dumps()`` call used to generate the response.
.. versionchanged:: 1.9
The ``json_dumps_params`` argument was added.
Usage
-----

View File

@ -545,6 +545,10 @@ Requests and Responses
* Added :meth:`HttpRequest.get_port() <django.http.HttpRequest.get_port>` to
fetch the originating port of the request.
* Added the ``json_dumps_params`` parameter to
:class:`~django.http.JsonResponse` to allow passing keyword arguments to the
``json.dumps()`` call used to generate the response.
Tests
^^^^^

View File

@ -504,6 +504,10 @@ class JsonResponseTests(SimpleTestCase):
response = JsonResponse({}, encoder=CustomDjangoJSONEncoder)
self.assertEqual(json.loads(response.content.decode()), {'foo': 'bar'})
def test_json_response_passing_arguments_to_json_dumps(self):
response = JsonResponse({'foo': 'bar'}, json_dumps_params={'indent': 2})
self.assertEqual(response.content.decode(), '{\n "foo": "bar"\n}')
class StreamingHttpResponseTests(SimpleTestCase):
def test_streaming_response(self):