Django框架之DRF 基于mixins来封装的视图详解

yipeiwu_com5年前Python基础

基础视图

示例环境搭建:新建一个Django项目,连接Mysql数据库,配置路由、视图函数、序列化单独创建py文件

# 配置路由

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
 url(r'^admin/', admin.site.urls),
 url(r'^PublishView/', views.PublishView.as_view()),
 url(r'^PublishDetailView/(?P<pk>\d+)', views.PublishDetailView.as_view()),

]
# 视图:

from django.shortcuts import render
from rest_framework.views import APIView
from app01 import models
from app01.MySer import BookSer,PublishSer,AuthorSer
from rest_framework.response import Response
# Create your views here.
# 基本视图

class PublishView(APIView):

 def get(self,request):
  publish_list = models.Publish.objects.all()
  bs = PublishSer(publish_list, many=True)
  return Response(bs.data)

 def post(self, request):
  bs = PublishSer(data=request.data)
  if bs.is_valid():
   bs.save()
   return Response(bs.data)
  else:
   return Response(bs.errors)

class PublishDetailView(APIView):
 def get(self, request, pk):
  publish_obj = models.Publish.objects.filter(pk=pk).first()
  bs = PublishSer(publish_obj, many=False)
  return Response(bs.data)

 def put(self, request, pk):
  publish_obj = models.Publish.objects.filter(pk=pk).first()
  bs = PublishSer(data=request.data, instance=publish_obj)
  if bs.is_valid():
   bs.save()
   return Response(bs.data)
  else:
   return Response(bs.data)

 def delete(self, request, pk):
  models.Publish.objects.filter(pk=pk).delete()
  return Response("")
# MySer.py

from rest_framework import serializers
from app01 import models

class BookSer(serializers.ModelSerializer):
 class Meta:
  model = models.Book
  fields = '__all__'


class PublishSer(serializers.ModelSerializer):
 class Meta:
  model = models.Publish
  fields = '__all__'


class AuthorSer(serializers.ModelSerializer):
 class Meta:
  model = models.Author
  fields = '__all__'

基于mixins来封装的视图

其它不变,更改视图:

# 基于mixins来封装的视图
from rest_framework.mixins import CreateModelMixin,\
         ListModelMixin,\
         RetrieveModelMixin,\
         DestroyModelMixin,\
         UpdateModelMixin
from rest_framework.generics import GenericAPIView

class PublishView(CreateModelMixin, ListModelMixin, GenericAPIView):
 queryset = models.Publish.objects.all()
 serializer_class = PublishSer
 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 PublishDetailView(RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin, GenericAPIView):
 queryset = models.Publish.objects.all()
 serializer_class = PublishSer
 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)

可以看出视图类中还是有很多冗余代码

mixins封装再封装,第三种方法

# 第三种写法:
from rest_framework.generics import CreateAPIView,\
         ListCreateAPIView,\
         DestroyAPIView,\
         RetrieveUpdateDestroyAPIView

class PublishView(ListCreateAPIView):
 queryset = models.Publish.objects.all()
 serializer_class = PublishSer

class PublishDetailView(RetrieveUpdateDestroyAPIView):
 queryset = models.Publish.objects.all()
 serializer_class = PublishSer

还是有冗余代码

第四种写法,再次封装,全部写在一个类中

# 路由
from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
 url(r'^admin/', admin.site.urls),

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

]
# 第四种写法:5个接口写在一个类中
from rest_framework.viewsets import ModelViewSet
class PublishView(ModelViewSet):
 queryset = models.Publish.objects.all()
 serializer_class = PublishSer

补充:

from rest_framework.viewsets import ViewSetMixin
from rest_framework.views import APIView
# ViewSetMixin 重写了as_view方法
class Test(ViewSetMixin,APIView):

 def aaa(self,request):
  return Response()

以上这篇Django框架之DRF 基于mixins来封装的视图详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

在python中实现同行输入/接收多个数据的示例

在python中实现同行输入/接收多个数据的示例

在使用python去AC题时总会遇到这样的问题,题目要求同行输入一组数据,但是你使用input时却不能做到,导致不断的CE,这个时候怎么样来解决的这个问题呢? 很简单,只需要使用inpu...

Python实现的凯撒密码算法示例

Python实现的凯撒密码算法示例

本文实例讲述了Python实现的凯撒密码算法。分享给大家供大家参考,具体如下: 一 介绍 凯撒密码是一种非常古老的加密方法,相传当年凯撒大地行军打仗时为了保证自己的命令不被敌军知道,就使...

Redis使用watch完成秒杀抢购功能的代码

redis使用watch完成秒杀抢购功能: 使用redis中两个key完成秒杀抢购功能,mywatchkey用于存储抢购数量和mywatchlist用户存储抢购列表。 它的优点如下: 1...

python重试装饰器示例

利用python 写一些网络服务的时候,当网络状况不好,或者资源占用过多,任务拥塞的情况下,总会抛出一些异常,当前任务就被终止了,可以很好的利用@装饰器,写一个重试的装饰器,这样比较py...

Python函数式编程指南(三):迭代器详解

3. 迭代器 3.1. 迭代器(Iterator)概述 迭代器是访问集合内元素的一种方式。迭代器对象从集合的第一个元素开始访问,直到所有的元素都被访问一遍后结束。 迭代器不能回退,只能往...