Python进阶41-drf框架(三)

2022-09-26 14:08:17 浏览数 (1)

  • 视图类传递参数给序列化类
  • 二次封装Response
  • 视图家族简介
    • generics APIView视图基类
    • mixins视图六大工具类
    • generic中的工具视图
    • 视图集viewsets
    • ModelViewSet拥有六大接口
    • 总结
    • 路由组件(了解)

-曾老湿, 江湖人称曾老大。


-多年互联网运维工作经验,曾负责过大规模集群架构自动化运维管理工作。 -擅长Web集群架构与自动化运维,曾负责国内某大型金融公司运维工作。 -devops项目经理兼DBA。 -开发过一套自动化运维平台(功能如下): 1)整合了各个公有云API,自主创建云主机。 2)ELK自动化收集日志功能。 3)Saltstack自动化运维统一配置管理工具。 4)Git、Jenkins自动化代码上线及自动化测试平台。 5)堡垒机,连接Linux、Windows平台及日志审计。 6)SQL执行及审批流程。 7)慢查询日志分析web界面。


视图类传递参数给序列化类


介绍

代码语言:javascript复制
# 1)在视图类中实例化序列化对象时,可以设置context内容
# 2)在序列化类中的局部钩子、全局钩子、create、update方法中,都可以用self.context访问视图类传递过来的内容


# 需求:
# 1) 在视图类中,可以通过request得到登陆用户request.user
# 2) 在序列化类中,要完成数据库数据的校验与入库操作,可能会需要知道当前的登陆用户,但序列化类无法访问request
# 3) 在视图类中实例化序列化对象时,将request对象传递进去

视图层

代码语言:javascript复制
class Book(APIView):
    def post(self, request, *args, **kwargs):
        book_ser = serializers.BookModelSerializer(data=request_data,context={'request':request})
        book_ser.is_valid(raise_exception=True)
        book_result = book_ser.save()
        return Response({
            'status': 0,
            'msg': 'ok',
            'results': serializers.BookModelSerializer(book_result).data
        })

序列化层

代码语言:javascript复制
class BookModelSerializer(ModelSerializer):
    class Meta:
        model = models.Book
        fields = ('name', 'price')
    def validate_name(self, value):
        print(self.context.get('request').method)
        return value

二次封装Response

我们之前在写视图的时候,发现写了大量的Response信息,反复写,反复写,重复代码,如下:

代码语言:javascript复制
return Response({
    'status': 1,
    'msg': '数据有误'
    })

return Response({
    'status': 0,
    'msg': 'put OK',
    'results': serializers.V2BookModelSerializer(book_obj).data
    })

封装

我们在项目目录下新创建一个目录:utils

然后再utils中创建response.py文件

代码语言:javascript复制
from rest_framework.response import Response

"""
Response({
    'status':0,
    'msg':'ok',
    'results':[],
    'token':'', # 有 这样的额外的key-value数据结果
},status=http_status,headers=headers,exceptio=True|False)


## 我们想要的结果,就是在APIResponse上加上括号就出来最简单的结果
APIResponse() => Respone({'status':0, 'msg':'ok',})
"""


class APIResponse(Response):
    def __init__(self, data_status=0, data_msg='ok', results=None, http_status=None, headers=None, exception=False,
                 **kwargs):
        data = {
            'status': data_status,
            'msg': data_msg
        }

        ## results可能是False、0等数据,这些数据某些情况下,也会作为合法数据返回
        if results is not None:
            data['results'] = results

        if kwargs is not None:
            for k, v in kwargs.items():
                setattr(data, k, v)  ## 反射,相当于:data[k] = v
        super().__init__(data=data, status=http_status, headers=headers, exception=exception)

测试

代码语言:javascript复制
from rest_framework.views import APIView
from rest_framework.response import Response

from . import models, serializers
## 导入
from utils.response import APIResponse

class V2Book(APIView):
    # 单查:有pk
    # 群查:无pk
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if pk:
            try:
                book_obj = models.Book.objects.get(pk=pk, is_delete=False)
                book_data = serializers.V2BookModelSerializer(book_obj).data
            except:
                return Response({
                    'status': 1,
                    'msg': '书籍不存在'
                })
        else:
            book_query = models.Book.objects.filter(is_delete=False).all()
            book_data = serializers.V2BookModelSerializer(book_query, many=True).data
        return Response({
            'status': 0,
            'msg': 'ok',
            'results': book_data
        })

    # 单增:传的数据是与model对应的字典
    # 群增:传的数据是 装多个 model对应字典 的列表
    def post(self, request, *args, **kwargs):
        request_data = request.data
        if isinstance(request_data, dict):
            many = False
        elif isinstance(request_data, list):
            many = True
        else:
            return Response({
                'status': 1,
                'msg': '数据有误',
            })
        book_ser = serializers.V2BookModelSerializer(data=request_data, many=many)
        # 当校验失败,马上终止当前视图方法,抛异常返回给前台
        book_ser.is_valid(raise_exception=True)
        book_result = book_ser.save()
        return Response({
            'status': 0,
            'msg': 'ok',
            'results': serializers.V2BookModelSerializer(book_result, many=many).data
        })

    # 单删:有pk
    # 群删:有pks   |  {"pks": [1, 2, 3]}
    def delete(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if pk:
            pks = [pk]
        else:
            pks = request.data.get('pks')
        if models.Book.objects.filter(pk__in=pks, is_delete=False).update(is_delete=True):
            return Response({
                'status': 0,
                'msg': '删除成功',
            })
        return Response({
            'status': 1,
            'msg': '删除失败',
        })

    # 单整体改,传的数据是与model对应的字典{name|price|publish|authors}
    def put(self, request, *args, **kwargs):
        request_data = request.data
        pk = kwargs.get('pk')
        old_book_obj = models.Book.objects.filter(pk=pk).first()
        ## 将众多 数据的校验交给序列化类来 处理,让序列化累扮演反序列化的角色,校验成功后,序列化帮你入库
        book_ser = serializers.V2BookModelSerializer(instance=old_book_obj, data=request_data)
        book_ser.is_valid(raise_exception=True)
        # 校验通过,完成数据的更新:要知道更新的目标,用来更新的新数据
        book_obj = book_ser.save()
        return Response({
            'status': 0,
            'msg': 'put OK',
            'results': serializers.V2BookModelSerializer(book_obj).data
        })

    # 单局部改
    def patch(self, request, *args, **kwargs):
        request_data = request.data
        pk = kwargs.get('pk')
        ## 将单改群改的数据都格式化成pks=[需要修改的对象主键标识] | request_data = [每个要修改对象对应的的修改数据]
        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 Response({
                        'status': 1,
                        'msg': '数据有误'
                    })
        else:
            return Response({
                'status': 1,
                'msg': '数据有误'
            })
        # 将不能操作的数据 剔除 pks与request_data数据筛选
        objs = []
        new_request_data = []
        for index, pk in enumerate(pks):
            try:
                ## pk对应的数据合理,将合理的对象存储
                obj = models.Book.objects.get(pk=pk, is_delete=False)
                objs.append(obj)
                new_request_data.append(request_data[index])
            except:
                # pk对应的数据有误,将对应索引的data中request_data中移除
                # index = pks.index(pk)
                # request_data.pop(index)
                continue

        book_ser = serializers.V2BookModelSerializer(instance=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.V2BookModelSerializer(book_objs, many=True).data
        return APIResponse(results=book_objs_data)

视图家族简介


介绍

代码语言:javascript复制
"""
views:视图
generics:工具视图
mixins:视图工具集
viewsets:视图集
"""


"""
学习曲线
APIView => GenericAPIView => mixins的五大工具类 => generics中的工具视图 => viewsets中的视图集
"""

generics APIView视图基类

先把之前序列化的东西保存下来,然后清空views文件,我们要开始学习视图了。


路由

代码语言:javascript复制
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^v1/books/$', views.BookAPIView.as_view()),
    url(r'^v1/books/(?P<pk>.*)/$', views.BookAPIView.as_view()),

    url(r'^v2/books/$', views.BookGenericAPIView.as_view()),
    url(r'^v2/books/(?P<pk>.*)/$', views.BookGenericAPIView.as_view()),
]

序列化

代码语言:javascript复制
from rest_framework.serializers import ModelSerializer, SerializerMethodField
from rest_framework.exceptions import ValidationError
from . import models
from rest_framework.serializers import ListSerializer


class BookListSerializer(ListSerializer):
    def update(self, instance, validated_data):
        for index, obj in enumerate(instance):
            self.child.update(obj, validated_data[index])
        return instance


class BookModelSerializer(ModelSerializer):
    class Meta:
        model = models.Book
        fields = ('name', 'price', 'img', 'author_list', 'publish_name', 'publish', 'authors')
        extra_kwargs = {
            'name': {
                'required': True,
                'min_length': 1,
                'error_messages': {
                    'required': '必填项',
                    'min_length': '太短',
                }
            },
            'publish': {
                'write_only': True
            },
            'authors': {
                'write_only': True
            },
            'img': {
                'read_only': True,
            },
            'author_list': {
                'read_only': True,
            },
            'publish_name': {
                'read_only': True,
            }
        }
        list_serializer_class = BookListSerializer

    def validate_name(self, value):
        if 'g' in value.lower():
            raise ValidationError('该g书不能出版')
        return value

    def validate(self, attrs):
        publish = attrs.get('publish')
        name = attrs.get('name')
        if models.Book.objects.filter(name=name, publish=publish):
            raise ValidationError({'book': '该书已存在'})
        return attrs

APIView视图

代码语言:javascript复制
from rest_framework.views import APIView
from utils.response import APIResponse
from . import models, serializers


class BookAPIView(APIView):
    def get(self, request, *args, **kwargs):
        book_query = models.Book.objects.filter(is_delete=False).all()
        book_ser = serializers.BookModelSerializer(book_query, many=True)
        book_data = book_ser.data
        return APIResponse(results=book_data)


GenericAPIView视图

代码语言:javascript复制
from rest_framework.views import APIView
from utils.response import APIResponse
from . import models, serializers
## GenericAPIView 是继承APIView的 ,完全兼容APIView
from rest_framework.generics import GenericAPIView


class BookGenericAPIView(GenericAPIView):
    def get(self, request, *args, **kwargs):
        book_query = models.Book.objects.filter(is_delete=False).all()
        book_ser = serializers.BookModelSerializer(book_query, many=True)
        book_data = book_ser.data
        return APIResponse(results=book_data)

代码没有改变,结果完全一样。


GenericAPIView视图对比APIView

重点:GenericAPIView在APIView的基础上完成了哪些事? 1.get_queryset() 2.get_object() 3.get_serializer()

修改代码如下:

代码语言:javascript复制
from rest_framework.views import APIView
from utils.response import APIResponse
from . import models, serializers

## GenericAPIView 是继承APIView的 ,完全兼容APIView
from rest_framework.generics import GenericAPIView

### 群取
class BookGenericAPIView(GenericAPIView):
    queryset = models.Book.objects.filter(is_delete=False).all()
    serializer_class = serializers.BookModelSerializer

    def get(self, request, *args, **kwargs):
        book_query = self.get_queryset()
        book_ser = self.get_serializer(book_query, many=True)
        book_data = book_ser.data
        return APIResponse(results=book_data)

我擦,本来的4步,变成了6步。

代码语言:javascript复制
from rest_framework.views import APIView
from utils.response import APIResponse
from . import models, serializers

## GenericAPIView 是继承APIView的 ,完全兼容APIView
from rest_framework.generics import GenericAPIView


class BookGenericAPIView(GenericAPIView):
    queryset = models.Book.objects.filter(is_delete=False).all()
    serializer_class = serializers.BookModelSerializer

## 单取
    def get(self, request, *args, **kwargs):
        book_query = self.get_object()
        book_ser = self.get_serializer(book_query)
        book_data = book_ser.data
        return APIResponse(results=book_data)

单取的路由,有名分组,必须叫pk,否则就会报错

代码语言:javascript复制
<api.views.BookGenericAPIView object at 0x112135470> - GET - Expected view BookGenericAPIView to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly.

总结: 1.get_queryset():从类属性queryset中获得model的queryset数据

2.get_object():从类属性queryset中获得model的queryset数据,再通过有名分组pk确定唯一操作对象 当然也可以自定义主键的有名分组名称lookup_field = 'id'

3.get_serializer():从类属性serializer_class中获得serializer的序列化类


单取,群取合并

代码语言:javascript复制
from rest_framework.views import APIView
from utils.response import APIResponse
from . import models, serializers


class BookAPIView(APIView):
    def get(self, request, *args, **kwargs):
        book_query = models.Book.objects.filter(is_delete=False).all()
        book_ser = serializers.BookModelSerializer(book_query, many=True)
        book_data = book_ser.data
        return APIResponse(results=book_data)

## GenericAPIView 是继承APIView的 ,完全兼容APIView
from rest_framework.generics import GenericAPIView


class BookGenericAPIView(GenericAPIView):
    queryset = models.Book.objects.filter(is_delete=False).all()
    serializer_class = serializers.BookModelSerializer

    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        return self.list(self, request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        return self.retrieve(self, request, *args, **kwargs)

    def list(self, request, *args, **kwargs):
        book_query = self.get_queryset()
        book_ser = self.get_serializer(book_query,many=True)
        book_data = book_ser.data
        return APIResponse(results=book_data)

    def retrieve(self, request, *args, **kwargs):
        book_query = self.get_object()
        book_ser = self.get_serializer(book_query)
        book_data = book_ser.data
        return APIResponse(results=book_data)

上面的代码能看懂,就看,看不懂也不要紧...不要'紧'的,为啥呢?因为别人帮我们干了...

mixins视图六大工具类


路由

代码语言:javascript复制
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^v1/books/$', views.BookAPIView.as_view()),
    url(r'^v1/books/(?P<pk>.*)/$', views.BookAPIView.as_view()),

    url(r'^v2/books/$', views.BookGenericAPIView.as_view()),
    url(r'^v2/books/(?P<pk>.*)/$', views.BookGenericAPIView.as_view()),

    url(r'^v3/books/$', views.BookListGenericAPIView.as_view()),
    url(r'^v3/books/(?P<pk>.*)/$', views.BookListGenericAPIView.as_view()),
]

视图

代码语言:javascript复制
from rest_framework.views import APIView
from utils.response import APIResponse
from . import models, serializers
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin


class BookListGenericAPIView(ListModelMixin, GenericAPIView):
    queryset = models.Book.objects.filter(is_delete=False)
    serializer_class = serializers.BookModelSerializer

    ## 群查
    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)


使用自定义的APIresponse

代码语言:javascript复制
class BookListGenericAPIView(ListModelMixin, GenericAPIView):
    queryset = models.Book.objects.filter(is_delete=False)
    serializer_class = serializers.BookModelSerializer

    ## 群查
    def get(self, request, *args, **kwargs):
        response = self.list(request, *args, **kwargs)
        return APIResponse(results=response.data)


实现增加方法

修改一下路由名称

代码语言:javascript复制
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^v1/books/$', views.BookAPIView.as_view()),
    url(r'^v1/books/(?P<pk>.*)/$', views.BookAPIView.as_view()),

    url(r'^v2/books/$', views.BookGenericAPIView.as_view()),
    url(r'^v2/books/(?P<pk>.*)/$', views.BookGenericAPIView.as_view()),

    url(r'^v3/books/$', views.BookMixinGenericAPIView.as_view()),
    url(r'^v3/books/(?P<pk>.*)/$', views.BookMixinGenericAPIView.as_view()),
]

修改方法名,添加增加方法

代码语言:javascript复制
class BookMixinGenericAPIView(ListModelMixin, CreateModelMixin, GenericAPIView):
    queryset = models.Book.objects.filter(is_delete=False)
    serializer_class = serializers.BookModelSerializer

    ## 群查
    def get(self, request, *args, **kwargs):
        response = self.list(request, *args, **kwargs)
        return APIResponse(results=response.data)

    def post(self, request, *args, **kwargs):
        response = self.create(request, *args, **kwargs)
        return APIResponse(results=response.data)


单查群查放一起

代码语言:javascript复制
from rest_framework.views import APIView
from utils.response import APIResponse
from . import models, serializers
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin


class BookMixinGenericAPIView(ListModelMixin, CreateModelMixin, RetrieveModelMixin, GenericAPIView):
    queryset = models.Book.objects.filter(is_delete=False)
    serializer_class = serializers.BookModelSerializer

    ## 群查
    def get(self, request, *args, **kwargs):
        if 'pk' in kwargs:
            response = self.retrieve(request, *args, **kwargs)
        else:
            response = self.list(request, *args, **kwargs)

        return APIResponse(results=response.data)

    def post(self, request, *args, **kwargs):
        response = self.create(request, *args, **kwargs)
        return APIResponse(results=response.data)


单改,群改

代码语言:javascript复制
from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin


class BookMixinGenericAPIView(ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, GenericAPIView):
    queryset = models.Book.objects.filter(is_delete=False)
    serializer_class = serializers.BookModelSerializer

    ## 查询
    def get(self, request, *args, **kwargs):
        if 'pk' in kwargs:
            ## 单查
            response = self.retrieve(request, *args, **kwargs)
        else:
            ## 群查
            response = self.list(request, *args, **kwargs)

        return APIResponse(results=response.data)
    
    ## 增加
    def post(self, request, *args, **kwargs):
        ## 单增
        response = self.create(request, *args, **kwargs)
        return APIResponse(results=response.data)

    ## 修改
    def put(self, request, *args, **kwargs):
        ## 单改
        response = self.update(request, *args, **kwargs)
        return APIResponse(results=response.data)

        ## 群改
    def patch(self, request, *args, **kwargs):
        response = self.partial_update(request, *args, **kwargs)
        return APIResponse(results=response.data)

generic中的工具视图

我们学了 Generic 视图 然后学了 Mixins 工具

接下来学习内容是drf中Generic结合了Mixins,工具视图


群查单增,路由

代码语言:javascript复制
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^v1/books/$', views.BookAPIView.as_view()),
    url(r'^v1/books/(?P<pk>.*)/$', views.BookAPIView.as_view()),

    url(r'^v2/books/$', views.BookGenericAPIView.as_view()),
    url(r'^v2/books/(?P<pk>.*)/$', views.BookGenericAPIView.as_view()),

    url(r'^v3/books/$', views.BookMixinGenericAPIView.as_view()),
    url(r'^v3/books/(?P<pk>.*)/$', views.BookMixinGenericAPIView.as_view()),

    url(r'^v4/books/$', views.BookListCreateAPIView.as_view()),
    url(r'^v4/books/(?P<pk>.*)/$', views.BookListCreateAPIView.as_view()),
]

群查单增,视图

代码语言:javascript复制
from rest_framework.generics import ListCreateAPIView

class BookListCreateAPIView(ListCreateAPIView):
    queryset = models.Book.objects.filter(is_delete=False)
    serializer_class = serializers.BookModelSerializer

四句话,完成群查和单增...

如果想要加上修改方法,不需要单独写,同样继承一下即可,还是4句话

代码语言:javascript复制
from rest_framework.generics import ListCreateAPIView, UpdateAPIView


class BookListCreateAPIView(ListCreateAPIView, UpdateAPIView):
    queryset = models.Book.objects.filter(is_delete=False)
    serializer_class = serializers.BookModelSerializer

视图集viewsets

重写了 as_view


视图

代码语言:javascript复制
from rest_framework.views import APIView
from utils.response import APIResponse
from . import models, serializers
from rest_framework.generics import GenericAPIView
from rest_framework.generics import ListCreateAPIView, UpdateAPIView


class BookListCreateAPIView(ListCreateAPIView, UpdateAPIView):
    queryset = models.Book.objects.filter(is_delete=False)
    serializer_class = serializers.BookModelSerializer
    
from rest_framework.viewsets import GenericViewSet
class BookGenericViewSet(GenericViewSet):
    queryset = models.Book.objects.filter(is_delete=False)
    serializer_class = serializers.BookModelSerializer
    ## 假装是群查
    def my_get_list(self, request, *args, **kwargs):
        return APIResponse(0,'假装这是群查,走到这肯定是成功了')

    ## 假装是单查
    def my_get_obj(self, request, *args, **kwargs):
        return APIResponse(0, '假装这是单查,走到这肯定是成功了')

路由

代码语言:javascript复制
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^v1/books/$', views.BookAPIView.as_view()),
    url(r'^v1/books/(?P<pk>.*)/$', views.BookAPIView.as_view()),

    url(r'^v2/books/$', views.BookGenericAPIView.as_view()),
    url(r'^v2/books/(?P<pk>.*)/$', views.BookGenericAPIView.as_view()),

    url(r'^v3/books/$', views.BookMixinGenericAPIView.as_view()),
    url(r'^v3/books/(?P<pk>.*)/$', views.BookMixinGenericAPIView.as_view()),

    url(r'^v4/books/$', views.BookListCreateAPIView.as_view()),
    url(r'^v4/books/(?P<pk>.*)/$', views.BookListCreateAPIView.as_view()),

    url(r'^v5/books/$', views.BookGenericViewSet.as_view({'get': 'my_get_list'})),
    url(r'^v5/books/(?P<pk>.*)/$', views.BookGenericViewSet.as_view({'get': 'my_get_obj'})),
]


完善单查和群查

代码语言:javascript复制
from rest_framework.views import APIView
from utils.response import APIResponse
from . import models, serializers
from rest_framework.generics import GenericAPIView
from rest_framework.viewsets import GenericViewSet
from rest_framework import mixins


class BookGenericViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet):
    queryset = models.Book.objects.filter(is_delete=False)
    serializer_class = serializers.BookModelSerializer

    ## 真·群查
    def my_get_list(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    ## 真·单查
    def my_get_obj(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

ModelViewSet拥有六大接口


路由

代码语言:javascript复制
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^v1/books/$', views.BookAPIView.as_view()),
    url(r'^v1/books/(?P<pk>.*)/$', views.BookAPIView.as_view()),

    url(r'^v2/books/$', views.BookGenericAPIView.as_view()),
    url(r'^v2/books/(?P<pk>.*)/$', views.BookGenericAPIView.as_view()),

    url(r'^v3/books/$', views.BookMixinGenericAPIView.as_view()),
    url(r'^v3/books/(?P<pk>.*)/$', views.BookMixinGenericAPIView.as_view()),

    url(r'^v4/books/$', views.BookListCreateAPIView.as_view()),
    url(r'^v4/books/(?P<pk>.*)/$', views.BookListCreateAPIView.as_view()),

    url(r'^v5/books/$', views.BookGenericViewSet.as_view({'get': 'my_get_list'})),
    url(r'^v5/books/(?P<pk>.*)/$', views.BookGenericViewSet.as_view({'get': 'my_get_obj'})),

    url(r'^v6/books/$', views.BookModelViewSet.as_view({'get': 'list', 'post': 'create'})),
    url(r'^v6/books/(?P<pk>.*)/$',views.BookModelViewSet.as_view({'get': 'retrieve', 'put': 'update', 'patch': 'partial_update'})),
]

视图

就下面几句话,六大接口搞定了...但是删除,一定要重写,否则会删除数据库

代码语言:javascript复制
from rest_framework.viewsets import ModelViewSet


class BookModelViewSet(ModelViewSet):
    queryset = models.Book.objects.filter(is_delete=False)
    serializer_class = serializers.BookModelSerializer

1.群查

2.单查

3.单增

4.单改


重写删除

视图

代码语言:javascript复制
from rest_framework.viewsets import ModelViewSet


class BookModelViewSet(ModelViewSet):
    queryset = models.Book.objects.filter(is_delete=False)
    serializer_class = serializers.BookModelSerializer

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        if not instance:
            return APIResponse(1, '删除失败')
        instance.is_delete = True
        instance.save()
        return APIResponse(0, '删除成功')

路由

代码语言:javascript复制
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^v1/books/$', views.BookAPIView.as_view()),
    url(r'^v1/books/(?P<pk>.*)/$', views.BookAPIView.as_view()),

    url(r'^v2/books/$', views.BookGenericAPIView.as_view()),
    url(r'^v2/books/(?P<pk>.*)/$', views.BookGenericAPIView.as_view()),

    url(r'^v3/books/$', views.BookMixinGenericAPIView.as_view()),
    url(r'^v3/books/(?P<pk>.*)/$', views.BookMixinGenericAPIView.as_view()),

    url(r'^v4/books/$', views.BookListCreateAPIView.as_view()),
    url(r'^v4/books/(?P<pk>.*)/$', views.BookListCreateAPIView.as_view()),

    url(r'^v5/books/$', views.BookGenericViewSet.as_view({'get': 'my_get_list'})),
    url(r'^v5/books/(?P<pk>.*)/$', views.BookGenericViewSet.as_view({'get': 'my_get_obj'})),

    url(r'^v6/books/$', views.BookModelViewSet.as_view({'get': 'list', 'post': 'create'})),
    url(r'^v6/books/(?P<pk>.*)/$',
        views.BookModelViewSet.as_view({'get': 'retrieve', 'put': 'update', 'patch': 'partial_update','delete':'destroy'})),
]

总结

GenericAPIView视图集

代码语言:javascript复制
# GenericAPIView是继承APIView的,使用完全兼容APIView
# 重点:GenericAPIView在APIView基础上完成了哪些事
# 1)get_queryset():从类属性queryset中获得model的queryset数据
# 2)get_object():从类属性queryset中获得model的queryset数据,再通过有名分组pk确定唯一操作对象
# 3)get_serializer():从类属性serializer_class中获得serializer的序列化类

mixins工具集

代码语言:javascript复制
# 1)mixins有五个工具类文件,一共提供了五个工具类,六个工具方法:单查、群查、单增、单删、单整体改、单局部改
# 2)继承工具类可以简化请求函数的实现体,但是必须继承GenericAPIView,需要GenericAPIView类提供的几个类属性和方法(见上方GenericAPIView基类知识点)
# 3)工具类的工具方法返回值都是Response类型对象,如果要格式化数据格式再返回给前台,可以通过 response.data 拿到工具方法返回的Response类型对象的响应数据

工具视图

代码语言:javascript复制
# 1)工具视图都是GenericAPIView的子类,且不同的子类继承了不听的工具类,重写了请求方法
# 2)工具视图的功能如果直接可以满足需求,只需要继承工具视图,提供queryset与serializer_class即可

视图集

代码语言:javascript复制
# 1)视图集都是优先继承ViewSetMixin类,再继承一个视图类(GenericAPIView或APIView)
#       GenericViewSet、ViewSet
# 2)ViewSetMixin提供了重写的as_view()方法,继承视图集的视图类,配置路由时调用as_view()必须传入 请求名-函数名 映射关系字典
#       eg: url(r'^v5/books/$', views.BookGenericViewSet.as_view({'get': 'my_get_list'})),
#       表示get请求会交给my_get_list视图函数处理

GenericAPIView 与 APIView 作为两大继承视图的区别

代码语言:javascript复制
# 1)GenericViewSet和ViewSet都继承了ViewSetMixin,as_view都可以配置 请求-函数 映射
# 2)GenericViewSet继承的是GenericAPIView视图类,用来完成标准的 model 类操作接口
# 3)ViewSet继承的是APIView视图类,用来完成不需要 model 类参与,或是非标准的 model 类操作接口
#       post请求在标准的 model 类操作下就是新增接口,登陆的post不满足
#       post请求验证码的接口,不需要 model 类的参与
# 案例:登陆的post请求,并不是完成数据的新增,只是用post提交数据,得到的结果也不是登陆的用户信息,而是登陆的认证信息

路由组件(了解)

代码语言:javascript复制
from django.conf.urls import include
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
# 所有路由与ViewSet视图类的都可以注册,会产生 '^v6/books/$' 和 '^v6/books/(?P<pk>[^/.] )/$'
router.register('v6/books', views.BookModelViewSet)

urlpatterns = [
    # 第一种添加子列表方式
    url(r'^', include(router.urls)),
]
# 第二种添加子列表方式
# urlpatterns.extend(router.urls)

0 人点赞