DRF响应类:Response
from rest_framework.response import Response
查看Response的源码:
def __init__(self, data=None, status=None, template_name=None, headers=None,
exception=False, content_type=None):
Response()括号内可以传入以下参数:
- data:响应的数据——空、字符串、数字、列表、字段、布尔
- status:网络状态码
- template_name:drf也可以支持前后台不分离返回页面,但是不能和data共存(不会涉及)
- headers:响应头(不用刻意去管)
- exception:是否异常响应(如果异常响应,可以赋值为True,没什么用)
- content_type:响应的结果类型(如果是响应data,默认就是application/json,所以不用管)
# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from . import models, serializers
class UserAPIView(APIView):
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk: # 单查
try:
obj = models.User.objects.get(pk=pk)
serializer = serializers.UserModelSerializer(obj, many=False)
return Response({
'status': 0,
'msg': 'ok',
'result': serializer.data
})
except:
return Response(
data={
'status': 1,
'msg': 'pk error'
},
status=status.HTTP_400_BAD_REQUEST, # 比直接写400更具有描述性
exception=True
)
二次封装Response
# 新建response.py文件
from rest_framework.response import Response
class APIResponse(Response):
def __init__(self, status=0, msg='ok', http_status=None, headers=None, exception=False, **kwargs):
# 将外界传入的数据状态码、状态信息以及其他所有额外存储在kwargs中的信息,都格式化成data数据
data = {
'status': status,
'msg': msg
}
# 在外界数据可以用result和results来存储
if kwargs:
data.update(kwargs)
super().__init__(data=data, status=http_status, headers=headers, exception=exception)
# 使用:
# APIResponse() 代表就返回 {"status": 0, "msg": "ok"}
# APIResponse(result="结果") 代表返回 {"status": 0, "msg": "ok", "result": "结果"}
# APIResponse(status=1, msg='error', http_status=400, exception=True) 异常返回 {"status": 1, "msg": "error"}