DRF视图组件

DRF视图组件:  

CVB模式继承----五层
from django.views import View  # Django的View
from rest_framework.views import APIView  # drf的APIView继承View
from rest_framework.generics import GenericAPIView, CreateAPIView  # drf的GenericAPIView继承APIView
# 以下CBV需要在路由的as_view()中添加对应参数---请求方式和函数的映射:无参数{'get':'list','post':'create'},带参数{'get':'retrive'}
from rest_framework.viewsets import GenericViewSet  # drf的GenericViewSet继承ViewSetMixin和GenericAPIView,路由改变:需指定请求方法--视图函数映射
from rest_framework.viewsets import ModelViewSet  # drf的ModelViewSet继承查(多条)、增、查(单条)、删、改和GenericViewSet,共有一个视图即可,路由有改变:需指定请求方法--视图函数(默认继承类处理)映射
 
一般多用APIView,对于基本的增删改查可直接使用ModelViewSet
 

models.py  

class UserGroup(models.Model):
    title = models.CharField(max_length=10)
models.py:

urls.py

 

drf主路由配置urls.py  

from django.conf.urls import url,include
urlpatterns = [
    url(r'^api/', include('api.urls')),
]
drf主路由配置urls.py:

api主路由配置urls.py:

from django.conf.urls import url
from api import views
 
urlpatterns = [
    
    # 继承APIView的路由写法
    url(r'^(?P<version>v[\d+])/groups1/$', views.UserGroupView1.as_view(), ),
    url(r'^(?P<version>v[\d+])/group1/(?P<pk>\d+)/$', views.UserGroupView11.as_view(), ),
 
    #继承GenericAPIView的路由写法
    url(r'^(?P<version>v[\d+])/groups2/$', views.UserGroupView2.as_view(), ),
    url(r'^(?P<version>v[\d+])/group2/(?P<pk>\d+)/$', views.UserGroupView22.as_view(), ),
 
    # 继承GenericViewSet的路由
    url(r'^(?P<version>v[\d+])/groups3/$', views.UserGroupView3.as_view({'get':'list','post':'create'}), ),
    url(r'^(?P<version>v[\d+])/group3/(?P<pk>\d+)/$', views.UserGroupView33.as_view({'get':'retrieve','put':'update','delete':'destroy'}), ),# 默认就是pk,或者自定义但需要指定但要在类中定义lookup_url_kwarg
 
    # 继承ModelViewSet的路由(执行同一个视图即可,有视图继承的不同类分别进行处理)
    url(r'^(?P<version>v[\d+])/groups4/$', views.UserGroupView4.as_view({'get': 'list', 'post': 'create'}), ),
    url(r'^(?P<version>v[\d+])/group4/(?P<pk>\d+)/$',
        views.UserGroupView4.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy'}), ),
    # 默认就是pk,或者自定义但需要指定但要在类中定义lookup_url_kwarg
 
]
 
api主路由配置urls.py:

views.py  

from django.shortcuts import render, HttpResponse
from rest_framework import serializers
from api import models
from rest_framework.response import Response#DRF自带,可自动进行序列化
 
 
#序列化器
class UserGroupSerializer1(serializers.ModelSerializer):
    class Meta:
        model = models.UserGroup
        fields = "__all__"
 
 #1.继承APIView的CBV写法
from rest_framework.views import APIView
class UserGroupView1(APIView):
    def get(self, request, *args, **kwargs):
        groups = models.UserGroup.objects.all()
        ser_groups = UserGroupSerializer1(instance=groups, many=True)
        ret = ser_groups.data
        return Response(ret)
 
    def post(self, request, *args, **kwargs):
        ser_data = UserGroupSerializer1(data=request.data)
        if ser_data.is_valid():  # 序列化器校验
            ser_data.save()  # 返回当前对象(序列化有instance就是更新)
        else:
            return Response(ser_data.errors)
        return self.get(request, *args, **kwargs)
class UserGroupView11(APIView):
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        group = models.UserGroup.objects.get(pk=pk)
        ser_group = UserGroupSerializer1(instance=group)  # many默认就是False
        ret = ser_group.data
        return Response(ret)
 
    def put(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        group = models.UserGroup.objects.get(pk=pk)
        ser_data = UserGroupSerializer1(instance=group, data=request.data)
        if ser_data.is_valid():
            r = ser_data.save()
            print(r)
        else:
            return Response(ser_data.errors)
        return self.get(request, *args, **kwargs)
 
    def patch(self, request, *args, **kwargs):
        pass
 
    def delete(self, request, *args, **kwargs):
        pass
 
#2.继承GenericAPIView的CBV写法(不实用--看源码)
from rest_framework.generics import GenericAPIView, CreateAPIView
class UserGroupView2(GenericAPIView):
    # filter_backends#配置过滤字段
    queryset = models.UserGroup.objects.all()
    serializer_class = UserGroupSerializer1#指定序列化器
    pagination_class = PageNumberPagination#自定分页类
 
    def get(self, request, *args, **kwargs):
        groups = self.get_queryset()
        page_groups = self.paginate_queryset(groups)
        ser_data = self.get_serializer(instance=page_groups, many=True)
        ret =ser_data.data
        return Response(ret)
    def post(self,request,*args,**kwargs):
        ser_data = UserGroupSerializer1(data=request.data)
        if ser_data.is_valid():  # 序列化器校验
            ser_data.save()  # 返回当前对象(序列化有instance就是更新)
        else:
            return Response(ser_data.errors)
        return self.get(request, *args, **kwargs)
 
class UserGroupView22(GenericAPIView):
    # filter_backends#配置过滤字段
    queryset = models.UserGroup.objects.all()
    serializer_class = UserGroupSerializer1
    lookup_field = 'pk'#指定字段(默认)--获取单个对象用
 
    def get(self, request, *args, **kwargs):
        obj = self.get_object()
        ser_data = self.get_serializer(instance=obj,many=False)
        ret = ser_data.data
        return Response(ret)
 
    def put(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        pass
 
    def delete(self, request, *args, **kwargs):
        pass
 
 
#3.继承GenericViewSet的CBV写法(注意路由的改变--请求与函数映射,函数名可自定义或采用默认,但必须对应)
from rest_framework.viewsets import GenericViewSet
class UserGroupView3(GenericViewSet):
    queryset = models.UserGroup.objects.all()
    serializer_class = UserGroupSerializer1
    pagination_class = PageNumberPagination
    def list(self, request, *args, **kwargs):
        groups = self.get_queryset()
        page_groups = self.paginate_queryset(groups)
        ser_data = self.get_serializer(instance=page_groups, many=True)
        ret =ser_data.data
        return Response(ret)
    def create(self,request,*args,**kwargs):
        ser_data = UserGroupSerializer1(data=request.data)
        if ser_data.is_valid():  # 序列化器校验
            ser_data.save()  # 返回当前对象(序列化有instance就是更新)
        else:
            return Response(ser_data.errors)
        return Response('post--create--ok!')
 
class UserGroupView33(GenericViewSet):
    queryset = models.UserGroup.objects.all()
    serializer_class = UserGroupSerializer1
    lookup_field = 'pk'#指定字段(默认)--获取单个对象用
 
    def retrieve(self, request, *args, **kwargs):
        obj = self.get_object()
        ser_data = self.get_serializer(instance=obj, many=False)
        ret = ser_data.data
        return Response(ret)
 
    def update(self, request, *args, **kwargs):
        obj = self.get_object()#获取当前对象通过指定字段lookup_field
        ser_data = self.get_serializer(instance=obj,data=request.data, many=False)
        if ser_data.is_valid():
            ser_data.save()
        else:
            return Response(ser_data.errors)
        return HttpResponse('put--update--ok!')
 
    def destroy(self, request, *args, **kwargs):
        models.UserGroup.objects.get(pk=self.lookup_field).delete()
        return HttpResponse('delete--destroy--ok!')
 
#4.继承ModelViewSet(继承6个类)的CBV写法(注意路由的改变--请求与函数(采用默认的类自己处理)映射)#针对简单的增删改查适用
from rest_framework.viewsets import ModelViewSet
class UserGroupView4(ModelViewSet):
    queryset = models.UserGroup.objects.all()
    serializer_class = UserGroupSerializer1
    pagination_class = PageNumberPagination
    lookup_field = 'pk'  # 指定字段(默认)--获取单个对象用(改/删/查单个)注意与url中对应
views.py:

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'api.apps.ApiConfig',
    'rest_framework',
]
 
REST_FRAMEWORK = {
    # 版本组件
    'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.URLPathVersioning',  # 设置版本组件类
    'DEFAULT_VERSION': 'v1',  # 默认的API版本
    'ALLOWED_VERSIONS': ['v1', 'v2'],  # 允许的API版本
    'VERSION_PARAM': 'version',  # 版本的key,默认的就是version(注意要和api接口中的key对应)
 
    # 解析器组件
    'DEFAULT_PARSER_CLASSES': ['rest_framework.parsers.JSONParser', 'rest_framework.parsers.FormParser', ],
    # 可指定多个解析器,不配置默认支持所有
 
    # 分页组件
    'PAGE_SIZE': 3
 
}
settings.py

 

 

 

CVB模式继承----五层

from django.views import View  # DjangoView

from rest_framework.views import APIView  # drfAPIView继承View

from rest_framework.generics import GenericAPIView, CreateAPIView  # drfGenericAPIView继承APIView

# 以下CBV需要在路由的as_view()中添加对应参数---请求方式和函数的映射:无参数{'get':'list','post':'create'},带参数{'get':'retrive'}

from rest_framework.viewsets import GenericViewSet  # drfGenericViewSet继承ViewSetMixinGenericAPIView,路由改变:需指定请求方法--视图函数映射

from rest_framework.viewsets import ModelViewSet  # drfModelViewSet继承查(多条)、增、查(单条)、删、改和GenericViewSet,共有一个视图即可,路由有改变:需指定请求方法--视图函数(默认继承类处理)映射

 

一般多用APIView,对于基本的增删改查可直接使用ModelViewSet

 

 

posted @ 2019-09-23 17:28  笑得好美  阅读(258)  评论(0编辑  收藏  举报