DRF框架之视图方法的几个封装好的模块介绍(第三天)

时间:2021-06-27 20:43:14

1.DRF框架给我们封装好了好多层模块的 来实现简便接口的编写

# from rest_framework.mixins import CreateModelMixin, UpdateModelMixin, RetrieveModelMixin, ListModelMixin, \
# DestroyModelMixin
# from rest_framework.generics import GenericAPIView
#
#这里是加载drf框架的mixins 模块的功能
#ListModelMixin 是给get 获取多本书接口使用
#CreateModelMixin 是给post接口用的
#UpdateModelMixin 是给put 接口使用的
#RetrieveModelMixin 是给get 单本书的接口使用的
#DestroyModelMixin 是给delete 接口使用的 #GenericAPIView 注意!!!!使用mixins模块一定也要加载这个模块,不然无法通过django的验证功能 #
# class Booksview(CreateModelMixin, ListModelMixin, GenericAPIView): # serializer_class = BookSerializers #使用序列化功能,之前写好的显示的内容
# queryset = models.Book.objects.all() #对数据库的那个表进行操纵使用
#
# def post(self, request, *args, **kwargs):
# return self.create(request, *args, **kwargs) #post的接口
#
# def get(self, request, *args, **kwargs):
# return self.list(request, *args, **kwargs) #get所有数据的接口
#
#
# class Bookview(RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin,GenericAPIView):
# serializer_class = BookSerializers
# queryset = models.Book.objects.all()
#
# def put(self, request, *args, **kwargs): #put接口 修改内容
# return self.update(request, *args, **kwargs)
#
# def get(self, request, *args, **kwargs): #get单个信息的接口
# return self.retrieve(request, *args, **kwargs)
#
# def delete(self, request, *args, **kwargs): #delete 接口删除用的
# return self.destroy(request, *args, **kwargs)

通过mixin组件实现

2. 更简便的方法来实现五种请求方式

#第三层:使用generics 下ListCreateAPIView,RetrieveUpdateDestroyAPIView

# from rest_framework.generics import ListAPIView,ListCreateAPIView,RetrieveUpdateDestroyAPIView,DestroyAPIView,CreateAPIView
# #它有两个接口,一个是获取所有,一个是新增
# class BooksView(ListCreateAPIView):
# serializer_class=BookSerializer
# queryset=models.Book.objects.all()
#
# class BookView(RetrieveUpdateDestroyAPIView):
# serializer_class=BookSerializer
# queryset=models.Book.objects.all()

ListCreateAPIView,RetrieveUpdateDestroyAPIView

3. 最终使用的也是最难的,灵活度最高的

#最终,一般用的时候,会经常用ViewSetMixin
#ViewSetMixin干了什么事?重写了as_view方法
# from rest_framework.viewsets import ViewSetMixin
# class Publish(ViewSetMixin,APIView):
#
# def aa(self,request):
# return HttpResponse('aa')
# def bb(self,request):
# return HttpResponse('aa')
# def cc(self,request):
# return HttpResponse('aa')
# def dd(self,request):
# return HttpResponse('aa')
# def get_all(self,request):
# pass
# def get_one(self,request):
# pass
# def create(self,request):
# pass
# def create_by_id(self,request):
# pass
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
# url(r'^books/$', views.BooksView.as_view()),
# url(r'^books/(?P<pk>\d+)', views.BookView.as_view()), # url(r'^test', views.Publish.as_view({'get':'aa'})),
# url(r'^xx', views.Publish.as_view({'post':'cc'})),

路由层配置的