Skip to content

Instantly share code, notes, and snippets.

@Cguilliman
Created November 15, 2019 07:41
Show Gist options
  • Save Cguilliman/36c4138091e99098092e6b3f149f22c6 to your computer and use it in GitHub Desktop.
Save Cguilliman/36c4138091e99098092e6b3f149f22c6 to your computer and use it in GitHub Desktop.
from typing import Dict, Any
from django.http.response import JsonResponse
from rest_framework.response import Response
BASE_RESPONSE_MESSAGE = {
'code': 200,
'meta': {},
'data': {}
}
class BaseResponseMixin:
base_response_message = None
meta_data = None
def get_status_code(self, response) -> int:
return response.status_code
def get_response_data(self, response) -> Any:
return getattr(response, 'data', {})
def get_response_meta(self, response=None) -> Dict:
return self.meta_data or {}
def get_response_content(self, response) -> Dict:
message = self.base_response_message or BASE_RESPONSE_MESSAGE
message.update({
'code': self.get_status_code(response),
'meta': self.get_response_meta(response),
'data': self.get_response_data(response)
})
return message
def send_response(self, response, data) -> JsonResponse:
return JsonResponse(data=data)
class BaseRestResponseMixin(BaseResponseMixin):
def send_response(self, response, data) -> Response:
return Response(
data,
status=response.status_code,
headers=response._headers
)
class BasePostResponseMixin:
def post(self, request, *args, **kwargs):
response = super().post(request, *args, **kwargs)
return self.send_response(response, self.get_response_content(response))
class BaseGetResponseMixin:
def get(self, request, *args, **kwargs):
response = super().get(request, *args, **kwargs)
return self.send_response(response, self.get_response_content(response))
class BasePutResponseMixin:
def put(self, request, *args, **kwargs):
response = super().put(request, *args, **kwargs)
return self.send_response(response, self.get_response_content(response))
def patch(self, request, *args, **kwargs):
response = super().patch(request, *args, **kwargs)
return self.send_response(response, self.get_response_content(response))
class BaseDeleteResponseMixin:
def delete(self, request, *args, **kwargs):
response = super().delete(request, *args, **kwargs)
return self.send_response(response, self.get_response_content(response))
class RestGetResponseMixin(BaseGetResponseMixin, BaseRestResponseMixin):
pass
class RestDeleteResponseMixin(BaseDeleteResponseMixin, BaseRestResponseMixin):
pass
class RestPostResponseMixin(BasePostResponseMixin, BaseRestResponseMixin):
pass
class RestPutResponseMixin(BasePutResponseMixin, BaseRestResponseMixin):
pass
class RestResponseMixin(BasePostResponseMixin, BaseGetResponseMixin, BaseRestResponseMixin):
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment