class UnsafeResponseSerializerMixin(object): """ Apply this mixin to any view or viewset to automatically use a different response serializer on POST, PUT or PATCH requests. Override 'get_response_data' method to return back the desired data, or 'get_response' method to also provide additional changs to the returned Response. """ def get_response_data(self, request): pass def get_response(self, request, response): data = self.get_response_data(request) if data: response.data = data return response def __init__(self, **kwargs): super(UnsafeResponseSerializerMixin, self).__init__(**kwargs) if hasattr(self, 'post'): self.post = self._post if hasattr(self, 'put'): self.put = self._put if hasattr(self, 'patch'): self.patch = self._patch def _post(self, request, *args, **kwargs): response = super(UnsafeResponseSerializerMixin, self).post(request, *args, **kwargs) return self.get_response(request, response) def _put(self, request, *args, **kwargs): response = super(UnsafeResponseSerializerMixin, self).put(request, *args, **kwargs) return self.get_response(request, response) def _patch(self, request, *args, **kwargs): response = super(UnsafeResponseSerializerMixin, self).patch(request, *args, **kwargs) return self.get_response(request, response)