07 DRF response class: Response

DRF response class: Response

from rest_framework.response import Response

View Response source:

def __init__(self, data=None, status=None, template_name=None, headers=None,
                                 exception=False, content_type=None):

Brackets Response () can pass the following parameters:

  • data: Data Response - empty strings, numbers, a list of fields, Boolean
  • status: Network Status Code
  • template_name: drf be supported without separating the front and back pages to return, but not co-exist, and data (not involve)
  • headers: response headers (never have to pipe)
  • exception: if an abnormal response (if abnormal response, can be assigned to True, no use)
  • content_type: Results type of response (if the response data, the default is application / json, so no tubes)
# 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
                )

Second package 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"}

Guess you like

Origin www.cnblogs.com/cnhyk/p/12458933.html