封装一个CommonResponse对象
需求: 封装CommonResponse对象使用方法如下
return CoomonResponse('100','成功',boo_ser.data)
return CoomonResponse('101','验证失败',boo_ser.errors)
实现:
from rest_framework.response import Response
class CommonResponse(Response):
def __init__(self, code=1000, messages='ok', results=None,
status=None, template_name=None, headers=None,
exception=False, content_type=None,
**kwargs):
data = {
'code': code,
'messages': messages,
}
data.update(kwargs)
if results:
data['results'] = results
super().__init__(data=data, status=status,
template_name=template_name, headers=headers,
exception=exception, content_type=content_type)
视图中使用:
class BookListCrateView(GenericAPIView):
# queryset = Book.objects.all()
queryset = Book.objects
serializer_class = BookModelSerializer
def get(self, request):
book_obj = self.get_queryset()
serializer = self.get_serializer(instance=book_obj, many=True)
return CommonResponse(results=serializer.data)
def post(self, request):
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
serializer.save()
obj = CommonResponse(results=serializer.data)
else:
obj = CommonResponse(2000, '失败', error=serializer.errors)
return obj