一、封装

可以发现在给客户端返回数据都有固定的格式,比如 json。我们为了减少重复代码,重写Response 类

utils/response.py

from rest_framework.response import Response


class APIResponse(Response):
def __init__(self, data_status=0, data_msg='ok', results=None, http_status=None, headers=None, exception=False,
**kwargs):
# data 的初始状态:状态码与状态信息
data = {
'status': data_status,
'msg': data_msg,
}
# data 的响应数据体
if results is not None:
data['results'] = results
# data 响应的其他内容
data.update(kwargs)
from rest_framework.response import Response


class APIResponse(Response):
def __init__(self, data_status=0, data_msg='ok', results=None, http_status=None, headers=None, exception=False,
**kwargs):
# data 的初始状态:状态码与状态信息
data = {
'status': data_status,
'msg': data_msg,
}
# data 的响应数据体
if results is not None:
data['results'] = results
# data 响应的其他内容
data.update(kwargs)
super().__init__(data=data, status=http_status, headers=headers,
exception=exception)

二、调用

views.py

from rest_framework.response import Response
from rest_framework.views import APIView

from api import models, serializers
from utils.response import APIResponse


class BookV2(APIView):
def patch(self, request, *args, **kwargs):
request_data = request.data
pk = kwargs.get('pk')
if pk and isinstance(request_data, dict):
pks = [pk]
request_data = [request_data]
elif not pk and isinstance(request_data, list):
pks = []
for dic in request_data:
pk = dic.pop('pk', None)
if pk:
pks.append(pk)
else:
return APIResponse(1, 'list data error')
else:
return APIResponse(2, 'data error')
pks_objs = []
new_request_data = []
for index, pk in enumerate(pks):
try:
obj = models.Book.objects.get(pk=pk, is_delete=False)
pks_objs.append(obj)
new_request_data.append(request_data[index])
except:
continue

book_ser = serializers.BookV2ModelSerializer(instance=pks_objs, data=new_request_data, partial=True, many=True)
book_ser.is_valid(raise_exception=True)
book_objs = book_ser.save()

book_objs_data = serializers.BookV2ModelSerializer(book_objs, many=True).data
return APIResponse(results=book_objs_data, http_status=201, token=from rest_framework.response import Response
from rest_framework.views import APIView

from api import models, serializers
from utils.response import APIResponse


class BookV2(APIView):
def patch(self, request, *args, **kwargs):
request_data = request.data
pk = kwargs.get('pk')
if pk and isinstance(request_data, dict):
pks = [pk]
request_data = [request_data]
elif not pk and isinstance(request_data, list):
pks = []
for dic in request_data:
pk = dic.pop('pk', None)
if pk:
pks.append(pk)
else:
return APIResponse(1, 'list data error')
else:
return APIResponse(2, 'data error')
pks_objs = []
new_request_data = []
for index, pk in enumerate(pks):
try:
obj = models.Book.objects.get(pk=pk, is_delete=False)
pks_objs.append(obj)
new_request_data.append(request_data[index])
except:
continue

book_ser = serializers.BookV2ModelSerializer(instance=pks_objs, data=new_request_data, partial=True, many=True)
book_ser.is_valid(raise_exception=True)
book_objs = book_ser.save()

book_objs_data = serializers.BookV2ModelSerializer(book_objs, many=True).data
return APIResponse(results=book_objs_data, http_status=201, token="mytoken")

三、测试接口

正常返回

mark

list error

mark

data error

mark