自定义返回响应
目前我们返回的数据样式是这样
{
"next": "http://127.0.0.1:8000/api/v1/games/?cursor=cD0x",
"previous": null,
"results": [
{
"id": 1,
"name": "老马",
"status": 0
}
]
}
或
{
"id": 1,
"name": "老马",
"status": 0
}
还是那句话,返回这样格式的数据,对于移动端是不友好的,所以我们需要自定义返回消息,返回的结构如下
{
"code": 200,
"message": "success",
"data": [
{
"id": 1,
"name": "老马",
"status": 0
}
],
"next": "http://127.0.0.1:8000/api/v1/games/?cursor=cD0x",
"previous": null
}
或者
{
"code": 200,
"message": "success",
"data": {
"id": 1,
"name": "老马",
"status": 0
}
}
自定义JSONResponse
创建一个custom_json_response.py
文件
from django.utils import six
from rest_framework.response import Response
from rest_framework.serializers import Serializer
class JsonResponse(Response):
"""
An HttpResponse that allows its data to be rendered into
arbitrary media types.
"""
def __init__(self, data=None, code=None, msg=None,
status=None,
template_name=None, headers=None,
exception=False, content_type=None, **kwargs):
"""
Alters the init arguments slightly.
For example, drop 'template_name', and instead use 'data'.
Setting 'renderer' and 'media_type' will typically be deferred,
For example being set automatically by the `APIView`.
"""
super(Response, self).__init__(None, status=status)
if isinstance(data, Serializer):
msg = (
'You passed a Serializer instance as data, but '
'probably meant to pass serialized `.data` or '
'`.error`. representation.'
)
raise AssertionError(msg)
self.data = {"code": code, "message": msg, "data": data}
self.data.update(kwargs)
self.template_name = template_name
self.exception = exception
self.content_type = content_type
if headers:
for name, value in six.iteritems(headers):
self[name] = value
自定义ModelViewSet
创建custom_model_view_set.py
文件
from rest_framework import status
from rest_framework import viewsets
from .custom_json_response import JsonResponse
class CustomModelViewSet(viewsets.ModelViewSet):
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return JsonResponse(data=serializer.data, msg="success", code=201, status=status.HTTP_201_CREATED,
headers=headers)
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return JsonResponse(data=serializer.data, code=200, msg="success", status=status.HTTP_200_OK)
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.get_serializer(instance)
return JsonResponse(data=serializer.data, code=200, msg="success", status=status.HTTP_200_OK)
def update(self, request, *args, **kwargs):
partial = kwargs.pop('partial', False)
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
if getattr(instance, '_prefetched_objects_cache', None):
# If 'prefetch_related' has been applied to a queryset, we need to
# forcibly invalidate the prefetch cache on the instance.
instance._prefetched_objects_cache = {}
return JsonResponse(data=serializer.data, msg="success", code=200, status=status.HTTP_200_OK)
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
self.perform_destroy(instance)
return JsonResponse(data=[], code=204, msg="delete resource success", status=status.HTTP_204_NO_CONTENT)
自定义分页类需要修改
from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination, CursorPagination
from .custom_json_response import JsonResponse
from rest_framework import status
class MyPageNumberPagination(PageNumberPagination):
page_size = 1
max_page_size = 1
page_size_query_param = 'size'
page_query_param = 'page'
def get_paginated_response(self, data):
return JsonResponse(data=data, code=200, msg="success", status=status.HTTP_200_OK, next=self.get_next_link(),
previous=self.get_previous_link(), count=self.page.paginator.count)
class MyPageNumberPagination(LimitOffsetPagination):
default_limit = 1
limit_query_param = 'limit'
offset_query_param = 'offset'
max_limit = 2
def get_paginated_response(self, data):
return JsonResponse(data=data, code=200, msg="success", status=status.HTTP_200_OK, next=self.get_next_link(),
previous=self.get_previous_link(), count=self.count)
class MyPageNumberPagination(CursorPagination):
cursor_query_param = 'cursor'
page_size = 1
ordering = 'id'
page_size_query_param = 'size'
max_page_size = 1
def get_paginated_response(self, data):
return JsonResponse(data=data, code=200, msg="success", status=status.HTTP_200_OK, next=self.get_next_link(),
previous=self.get_previous_link())
Generics
from rest_framework import status
from rest_framework import viewsets
from .custom_json_response import JsonResponse
from rest_framework import generics
class ListCreateAPIView(generics.ListCreateAPIView):
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return JsonResponse(data=serializer.data, msg="success", code=201, status=status.HTTP_201_CREATED,
headers=headers)
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return JsonResponse(data=serializer.data, code=200, msg="success", status=status.HTTP_200_OK)
class RetrieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.get_serializer(instance)
return JsonResponse(data=serializer.data, code=200, msg="success", status=status.HTTP_200_OK)
def update(self, request, *args, **kwargs):
partial = kwargs.pop('partial', False)
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
if getattr(instance, '_prefetched_objects_cache', None):
# If 'prefetch_related' has been applied to a queryset, we need to
# forcibly invalidate the prefetch cache on the instance.
instance._prefetched_objects_cache = {}
return JsonResponse(data=serializer.data, msg="success", code=200, status=status.HTTP_200_OK)
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
self.perform_destroy(instance)
return JsonResponse(data=[], code=204, msg="delete resource success", status=status.HTTP_204_NO_CONTENT)