drf 视图功能

视图

drf提供的视图功能

自己的第一次封装


#一个功能写成一个类,方便组合,只要继承它就可以有这个功能
#将功能都写在一个类中,可控性就会变差
from book.myserializers import BookSerializer, PublishSerializer
from rest_framework.response import Response

class List():
    def list(self, request, *args, **kwargs):
        list = self.model.objects.all()
            if list:
                ser = self.ser(instance=list, many=True)
                return Response(ser.data)
            return Response({"msg": '获取失败'})
        
class Get()
    def get(self, request, *args, **kwargs): 
        id = args[0]
        obj = self.model.objects.filter(pk=id).first()
        obj_ser = self.ser(instance=obj, many=False)
        return Response(obj_ser.data)

class Post():
    def post(self, request):
        res = {"staus": 100, "msg": "新增成功", "data": []}
        ser = self.ser(data=request.data)
        if ser.is_valid():
            ser.save()
            res["data"] = ser.data
        else:
            res["msg"] = "新增失败"
            res["data"] = ser.errors
        return Response(res)
    
class Put()
    def put(self, request, id, *args, **kwargs):
        res = {"staus": 100, "msg": "更新成功", "data": []}
        obj = self.model.objects.filter(pk=id).first()
        obj_ser = self.ser(data=request.data, instance=obj)
        if obj_ser.is_valid():
            obj_ser.save()
        else:
            res["msg"] = "更新失败"
            res["data"] = obj_ser.errors
        return Response(res)

class Delete():
    def delete(self, request, id, *args, **kwargs):
        print(1)
        res = {"staus": 100, "msg": "删除成功", "data": []}
        obj = self.model.objects.filter(pk=id).first()
        if obj:
            obj.delete()
            return Response(res)
        res["msg"] = "删除失败"
        return Response(res)

    
class Books(List,POST, APIView):
    model = Book
    ser = BookSerializer
class Books(Get,Delete,Put):
    model = Book
    ser = BookSerializer

drf的第一次封装

#新增方法
from rest_framework.mixins import CreateModelMixin
#删除方法
from rest_framework.mixins import DestroyModelMixin
#获取所有方法
from rest_framework.mixins import ListModelMixin
#更新方法
from rest_framework.mixins import UpdateModelMixin
#获取单个方法
from rest_framework.mixins import RetrieveModelMixin
#使用封装,不再继承APIView类,继承GenericAPIView(继承了APIView)
from rest_framework.generics import GenericAPIView


class Books(ListModelMixin,CreateModelMixin,GenericAPIView):
    #指定序列化类
    serializer_class = BookSerializer
    #对象们
    queryset = Book.objects.all()
    
    #必须写get方法的原因是父类没有get方法而是list方法
    def get(self,request,*args,**kwargs):
        return self.list(request,*args,**kwargs)

    def post(self,request,*args,**kwargs):
        return self.create(request,*args,**kwargs)

class MyBook(RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,GenericAPIView):
    serializer_class = BookSerializer
    #对象们,获取单个对象,所以url中必须以表中的字段分组
    queryset = Book.objects.all()
    '''
    以pk(主键)作为分组字段,以便retrieve方法内部筛选使用
    url(r'^books/(?P<pk>\d+)', views.MyBook.as_view(),),
    '''
    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)
 #第一次封装,都需要写类似的方法get,delete...

drf第二次封装

from rest_framework.generics import ListCreateAPIView
from rest_framework.generics import RetrieveUpdateDestroyAPIView

class Books(ListCreateAPIView):
    serializer_class = BookSerializer
    queryset = Book.objects.all()

class MyBook(RetrieveUpdateDestroyAPIView):
    serializer_class = BookSerializer
    queryset = Book.objects.all()
    
#可以不定义get,post方法的原因是父类中有get,post等方法

drf第三次封装


视图层
from rest_framework.viewsets import ModelViewSet
class Books(ModelViewSet):
    serializer_class = BookSerializer
    queryset = Book.objects.all()

路由层
url(r'^books/$', views.Books.as_view({'get':'list','post':'create'})),
 url(r'^books/(?P<pk>\d+)',views.Books.as_view({'get':'retrieve','put':'update','delete':'destroy'}),),
    
    

ViewSetMinix

1.#ModelViewSet继承了GenericViewSet
class ModelViewSet(mixins.CreateModelMixin,
                   mixins.RetrieveModelMixin,
                   mixins.UpdateModelMixin,
                   mixins.DestroyModelMixin,
                   mixins.ListModelMixin,
                   GenericViewSet):
    pass
2.#GenericViewSet继承了ViewSetMixin
class GenericViewSet(ViewSetMixin, generics.GenericAPIView):
    pass

3.#ViewSetMixin重写了view方法,
class ViewSetMixin(object):
    @classonlymethod
    def as_view(cls, actions=None, **initkwargs):     
        ...
        def view(request, *args, **kwargs):
            ...
            #method为请求:get,post...
            #actions为 路由中传入的字典
            #action为list,create都方法名
            #url(r'^books/$', views.Books.as_view({'get':'list','post':'create'}))
            '''
            def as_view(cls, actions=None, **initkwargs):
            '''
            for method, action in actions.items():
                handler = getattr(self, action)#获取函数地址
                setattr(self, method, handler)#将请求指向函数地址
            .....
            return self.dispatch(request, *args, **kwargs)
        ...
        return csrf_exempt(view)

nginx

什么是反向代理
什么是正向代理
1.负载均衡
2.动静分离(动态文件转给wsgi,静态文件直接去django取)
上一篇:DRF--重写views


下一篇:DRF的内置分页和筛选功能