2015-01-29 13:45:27 +00:00
|
|
|
import json
|
2015-06-08 15:32:55 +00:00
|
|
|
|
2015-01-29 13:45:27 +00:00
|
|
|
from django.core.serializers.json import DjangoJSONEncoder
|
|
|
|
from django.http import HttpResponse
|
|
|
|
|
|
|
|
|
|
|
|
# CLass JsonResponse see: https://github.com/django/django/blob/master/django/http/response.py#L456
|
|
|
|
|
|
|
|
class JsonResponse(HttpResponse):
|
|
|
|
"""
|
|
|
|
An HTTP response class that consumes data to be serialized to JSON.
|
|
|
|
:param data: Data to be dumped into json. By default only ``dict`` objects
|
|
|
|
are allowed to be passed due to a security flaw before EcmaScript 5. See
|
|
|
|
the ``safe`` parameter for more information.
|
|
|
|
:param encoder: Should be an json encoder class. Defaults to
|
|
|
|
``django.core.serializers.json.DjangoJSONEncoder``.
|
|
|
|
:param safe: Controls if only ``dict`` objects may be serialized. Defaults
|
|
|
|
to ``True``.
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True, **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')
|
|
|
|
kwargs.setdefault('content_type', 'application/json')
|
|
|
|
data = json.dumps(data, cls=encoder)
|
|
|
|
super(JsonResponse, self).__init__(content=data, **kwargs)
|