zoukankan      html  css  js  c++  java
  • 封装一个CommonResponse对象

    需求: 封装CommonResponse对象使用方法如下

    Copy
    return CoomonResponse('100','成功',boo_ser.data)
    return CoomonResponse('101','验证失败',boo_ser.errors)
    

    实现:

    Copy
    from rest_framework.response import Response
    
    
    class CommonResponse(Response):
        def __init__(self, code=1000, messages='ok', results=None,
                     status=None, template_name=None, headers=None,
                     exception=False, content_type=None,
                     **kwargs):
            data = {
                'code': code,
                'messages': messages,
            }
            data.update(kwargs)
            if results:
                data['results'] = results
            super().__init__(data=data, status=status,
                             template_name=template_name, headers=headers,
                             exception=exception, content_type=content_type)
    

    视图中使用:

    Copy
    class BookListCrateView(GenericAPIView):
        # queryset = Book.objects.all()
        queryset = Book.objects
        serializer_class = BookModelSerializer
    
        def get(self, request):
            book_obj = self.get_queryset()
            serializer = self.get_serializer(instance=book_obj, many=True)
            return CommonResponse(results=serializer.data)
    
        def post(self, request):
            serializer = self.get_serializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                obj = CommonResponse(results=serializer.data)
            else:
                obj = CommonResponse(2000, '失败', error=serializer.errors)
            return obj
    
  • 相关阅读:
    C语言的特点与缺点
    C语言的特点与缺点
    HDU1234 开门人和关门人
    HDU1234 开门人和关门人
    B00014 C++实现的AC自动机
    B00014 C++实现的AC自动机
    HDU4716 A Computer Graphics Problem
    HDU4716 A Computer Graphics Problem
    I00029 C语言程序-打印九九乘法表
    I00029 C语言程序-打印九九乘法表
  • 原文地址:https://www.cnblogs.com/Tornadoes-Destroy-Parking-Lots/p/13406023.html
Copyright © 2011-2022 走看看