Created
October 28, 2021 07:43
-
-
Save TSKGunGun/3a7cd73fcde038d63028d9dec7de9c70 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 a json encoder class. Defaults to | |
``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, | |
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, **json_dumps_params) | |
super().__init__(content=data, **kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment