Adding JsonResponseMixin

This commit is contained in:
László Károlyi 2023-09-11 15:44:23 +02:00
parent 5a340e3bd4
commit 40dab5fb46
Signed by: karolyi
GPG Key ID: 2DCAF25E55735BFE
1 changed files with 37 additions and 0 deletions

View File

@ -0,0 +1,37 @@
from django.conf import settings
from django.http.response import JsonResponse
from django.views.generic.base import ContextMixin, TemplateView, View
class JsonResponseMixin(ContextMixin, View):
"""
A mixin that can be used to render a JSON response. Override
`get_json_data()` and you're good to go.
"""
status_code = 200
def render_to_response(
self, context: dict, status_code: int | None = None,
**response_kwargs) -> JsonResponse:
"""
Returns a JSON response, transforming 'context' to make the
payload.
"""
json_dumps_params = {}
if settings.DEBUG:
json_dumps_params['indent'] = 2
return JsonResponse(
data=self.get_json_data(context=context),
status=status_code or self.status_code,
json_dumps_params=json_dumps_params,
**response_kwargs
)
def get_json_data(self, context: dict) -> dict:
"""
Returns an object that will be serialized as JSON by
`json.dumps()`.
"""
return {}
get = TemplateView.get