django-oidc-provider/openid_provider/lib/utils/http.py
niccolasmendoza@gmail.com cfbfbfc74a removing unnecesary imports
2015-06-08 12:32:55 -03:00

27 lines
1.1 KiB
Python

import json
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)