全面响应的Django REST框架自定义格式 [英] Django REST framework custom format for all out responses

查看:85
本文介绍了全面响应的Django REST框架自定义格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我将DRF用作后端,将Angular用作前端.

In my project I use DRF as backend and Angular as frontend.

Django == 1.10 djangorestframework == 3.7.1

Django==1.10 djangorestframework==3.7.1

我需要DRF的所有回复都采用以下格式.

I need all responses from DRF to be in the following format.

{
 "status": "",  //  200,400,.....etc
 "error": "",   //  True, False
 "data": [],    //  data
 "message": ""  //  Success messages
}

当前位于

[
    {
        "id": 1,
        "name": ""
    },
    {
        "id": 2,
        "name": ""
    }
]

应该是

{
     "status": "200",   
     "error": "False",      
     "data": [
               {
                   "id": 1,
                   "name": ""
                },
                {
                   "id": 2,
                   "name": ""
                }
            ],    
     "message": "Success"  
}

为此,我编写了一个自定义视图集并覆盖了功能列表,详细信息,创建,更新

for this i have written a custom viewset and overridden the functions list, detail, create, update

class ResponseModelViewSet(viewsets.ModelViewSet):
    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)
        custom_data = {
            "status": True,
            "error": False,
            "message": 'message',
            "data": serializer.data
        }
        return Response(custom_data)

    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)

        custom_data = {
            "status": True,
            "error": False,
            "message": 'message',
            "data": serializer.data
        }

        return Response(custom_data, status=status.HTTP_201_CREATED, headers=headers)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        custom_data = {
            "status": True,
            "error": False,
            "message": 'message',
            "data": serializer.data
        }
        return Response(custom_data)

    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 = {}

        custom_data = {
            "status": True,
            "error": False,
            "message": 'message',
            "data": serializer.data
        }
        return Response(custom_data)

在视图中,我使用自定义视图集

and in views i use my custom viewset

from common.baseview import ResponseModelViewSet

class PositionViewsets(ResponseModelViewSet):
    serializer_class = PositionSerializer
    permission_classes = (IsAuthenticated,)
    model = Position

    def get_queryset(self):
        return Position.objects.filter(order__user=self.request.user)

我不确定这是正确的方法还是其他有效的方法. 无论如何,这适用于我的自定义应用程序,但不适用于身份验证应用程序 我使用了默认的其余应用程序

I am not sure if this is the correct way of doing it or there is some other efficient way to do it. Anyway this works for my custom apps but not for the Authentication app i used the default rest apps

'rest_framework.authtoken',
'rest_auth',

使用用户名和密码登录并获得成功响应,如下所示.

For login using username and password and get the success response as follows.

{
    "key": "e642efd0b78e08b57bf34fa999f49b70a7bfe21a"
}

相反,我需要这个.

{
 "status": "200",   
 "error": "False",      
 "data": [
          {
           "token":{ 
                     "key":"e642efd0b78e08b57bf34fa999f49b70a7bfe21a"
                    }
           }
         ],     
 "message": "Login Sucess"  
}

错误

{
 "status": "error",     
 "error": "True",   
 "data": [
           {
            "email": ["Enter a valid email address."]
            }
         ],     
 "message": "Login Failed"  
}

推荐答案

经过研究,我找到了一种方法.我必须覆盖ModelViewSet的默认行为才能输出不同的响应.

After some research I found a way to do this. I had to override the default behaviour of the ModelViewSet to output a different response.

我最初创建了一种自定义的Response格式:

I created a custom Response format initially:

class ResponseInfo(object):
    def __init__(self, user=None, **args):
        self.response = {
            "status": args.get('status', True),
            "error": args.get('error', 200),
            "data": args.get('data', []),
            "message": args.get('message', 'success')
        }

然后在ModelViewSet的每种方法中使用此自定义格式:

Then use this custom format in every method of the ModelViewSet:

class ResponseModelViewSet(viewsets.ModelViewSet):
    def __init__(self, **kwargs):
        self.response_format = ResponseInfo().response
        super(ResponseModelViewSet, self).__init__(**kwargs)

    def list(self, request, *args, **kwargs):
        response_data = super(ResponseModelViewSet, self).list(request, *args, **kwargs)
        self.response_format["data"] = response_data.data
        self.response_format["status"] = True
        if not response_data.data:
            self.response_format["message"] = "List empty"
        return Response(self.response_format)

    def create(self, request, *args, **kwargs):
        response_data = super(ResponseModelViewSet, self).create(request, *args, **kwargs)
        self.response_format["data"] = response_data.data
        self.response_format["status"] = True
        return Response(self.response_format)

    def retrieve(self, request, *args, **kwargs):
        response_data = super(ResponseModelViewSet, self).retrieve(request, *args, **kwargs)
        self.response_format["data"] = response_data.data
        self.response_format["status"] = True
        if not response_data.data:
            self.response_format["message"] = "Empty"
        return Response(self.response_format)

    def update(self, request, *args, **kwargs):
        response_data = super(ResponseModelViewSet, self).update(request, *args, **kwargs)
        self.response_format["data"] = response_data.data
        self.response_format["status"] = True

        return Response(self.response_format)

    def destroy(self, request, *args, **kwargs):
        response_data = super(ResponseModelViewSet, self).destroy(request, *args, **kwargs)
        self.response_format["data"] = response_data.data
        self.response_format["status"] = True
        return Response(self.response_format)

这篇关于全面响应的Django REST框架自定义格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆