潮州+网站建设,jsp网站开发详解 下载,佛山外贸网站建设方案,中国最大免费h5游戏源码网站前面介绍了什么是符合RESTful规范的API接口#xff0c;以及使用了基于函数的视图(FBV)编写了对文章进行增删查改的API。在本篇文章将使用基于类的视图(Class-based View, CBV)重写之前的接口。
参考#xff1a;
1、Django开发总结#xff1a;Django MVT与MVC设计模式…前面介绍了什么是符合RESTful规范的API接口以及使用了基于函数的视图(FBV)编写了对文章进行增删查改的API。在本篇文章将使用基于类的视图(Class-based View, CBV)重写之前的接口。
参考
1、Django开发总结Django MVT与MVC设计模式请求过程与代码示例附源码_SteveRocket的博客-CSDN博客如果要开发一个好的网站或网络应用就必需了解经典的软件开发所遵循的MVC 设计模式。本篇详细总结软件开发所遵循的MVC (Model-View-Controller, 模型-视图-控制器) 设计模式以及Django的MVT设计模式(Model-View-Template)如何遵循这种设计理念。Django Model(模型), URL(链接), View(视图) 和Template(模板)又是如何遵循MVC软件设计模式的。https://blog.csdn.net/zhouruifu2015/article/details/129648966
https://blog.csdn.net/zhouruifu2015/article/details/129761750https://blog.csdn.net/zhouruifu2015/article/details/129761750
工程路径及APPdjango_framework\django_rest_framework_pro\drf_pro 基于类的视图(CBV)
一个中大型的Web项目代码量通常是非常大的如果全部使用函数视图写那么代码的复用率是非常低的。而使用类视图就可以有效的提高代码复用因为类是可以被继承的可以拓展的。特别是将一些可以共用的功能抽象成Mixin类或基类后可以减少重复造轮子的工作。
DRF推荐使用基于类的视图(CBV)来开发API, 并提供了4种开发CBV开发模式。
使用基础APIView类使用Mixins类和GenericAPI类混配使用通用视图generics.*类, 比如generics.ListCreateAPIView使用视图集ViewSet和ModelViewSet
类视图的比较
DRF提供了4种编写CBV类API的方式到底哪种CBV开发模式更好? 答案是各有利弊
基础的API类可读性最高代码最多灵活性最高。当需要对API行为进行个性化定制时建议使用这种方式。通用generics.*类可读性好代码适中灵活性较高。当需要对一个模型进行标准的增删查改全部或部分操作时建议使用这种方式。使用视图集viewset: 可读性较低代码最少灵活性最低。当需要对一个模型进行标准的增删查改的全部操作且不需定制API行为时建议使用这种方式。mixin类和GenericAPI的混用这个和generics.*类没什么区别不看也罢。Django视图集viewset代码最少但这是以牺牲了代码的可读性为代价的因为它对代码进行了高度地抽象化。另外urls由router生成不如自己手动配置的清楚。
使用CBV类可以简化代码增加代码重用在很多情况下还需要重写父类的方法比如get_queryset, get_serializer_class方法以实现特殊的功能。 使用APIView类
DRF的APIView类继承了Django自带的View类, 一样可以按请求方法调用不同的处理函数比如get方法处理GET请求post方法处理POST请求。不过DRF的APIView要强大得多。它不仅支持更多请求方法而且对Django的request对象进行了封装可以使用request.data获取用户通过POST, PUT和PATCH方法发过来的数据而且支持插拔式地配置认证、权限和限流类。 使用APIView类重写之前的函数视图
# drf_pro/views.py
# 基础APIView类
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from django.http import Http404
from .models import Article
from .serializers import ArticleSerializer2class ArticleList(APIView):List all articles, or create a new article.def get(self, request, formatNone):articles Article.objects.all()serializer ArticleSerializer2(articles, manyTrue)return Response(serializer.data)def post(self, request, formatNone):serializer ArticleSerializer2(datarequest.data)if serializer.is_valid():# 注意手动将request.user与author绑定serializer.save(authorrequest.user)return Response(serializer.data, statusstatus.HTTP_201_CREATED)return Response(serializer.errors, statusstatus.HTTP_400_BAD_REQUEST)class ArticleDetail(APIView):Retrieve, update or delete an article instance.def get_object(self, pk):try:return Article.objects.get(pkpk)except Article.DoesNotExist:raise Http404def get(self, request, pk, formatNone):article self.get_object(pk)serializer ArticleSerializer2(article)return Response(serializer.data)def put(self, request, pk, formatNone):article self.get_object(pk)serializer ArticleSerializer2(instancearticle, datarequest.data)if serializer.is_valid():serializer.save()return Response(serializer.data)return Response(serializer.errors, statusstatus.HTTP_400_BAD_REQUEST)def delete(self, request, pk, formatNone):article self.get_object(pk)article.delete()return Response(statusstatus.HTTP_204_NO_CONTENT)
或许已经注意到这段代码跟之前基于函数的视图差别并不大。最大不同的是不需要在对用户的请求方法进行判断。该视图可以自动将不同请求转发到相应处理方法逻辑上也更清晰。 修改url配置, 让其指向新的基于类的视图
# drf_pro/urls.py
from django.urls import re_path
from rest_framework.urlpatterns import format_suffix_patterns
from . import views, views_cbvurlpatterns [re_path(r^articles/$, views.article_list),re_path(r^articles/(?Ppk[0-9])$, views.article_detail),# 基于类的视图re_path(r^articles_cbv/$, views_cbv.ArticleList.as_view()),# http://localhost/v1/articles_cbv/re_path(r^articles_cbv/(?Ppk[0-9])$, views_cbv.ArticleDetail.as_view()),
]urlpatterns format_suffix_patterns(urlpatternsurlpatterns)
发送GET请求到v1/articles_cbv/将看到跟上文一样的效果 发送GET请求到v1/articles_cbv/4/ 根据id查看详情 使用Mixin类和GenericAPI类混配
使用基础APIView类并没有大量简化代码与增删改查操作相关的代码包括返回内容对所有模型几乎都是一样的。比如现在需要对文章类别Category模型也进行序列化和反序列化只需要复制Article视图代码将Article模型改成Category模型, 序列化类由ArticleSeralizer类改成CategorySerializer类就行了。
对于这些通用的增删改查行为DRF已经提供了相应的Mixin类。Mixin类可与generics.GenericAPI类联用灵活组合成所需要的视图。 使用Mixin类和generics.GenericAPI类重写的类视图
# drf_pro/views.py
# 使用Mixin类和generics.GenericAPI类重写的类视图
from rest_framework import mixins
from rest_framework import generics
class ArticleList2(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView):GenericAPIView 类继承了APIView类提供了基础的API视图。queryset Article.objects.all()serializer_class ArticleSerializer2def get(self, request, *args, **kwargs):return self.list(request, *args, **kwargs)def post(self, reqeust, *args, **kwargs):return self.create(reqeust, *args, **kwargs)
GenericAPIView 类继承了APIView类提供了基础的API视图。它对用户请求进行了转发并对Django自带的request对象进行了封装。不过它比APIView类更强大因为它还可以通过queryset和serializer_class属性指定需要序列化与反序列化的模型或queryset及所用到的序列化器类。 这里的 ListModelMixin 和 CreateModelMixin类则分别引入了.list() 和 .create() 方法当用户发送get请求时调用Mixin提供的list()方法将指定queryset序列化后输出发送post请求时调用Mixin提供的create()方法创建新的实例对象。 DRF还提供RetrieveModelMixin, UpdateModelMixin和DestroyModelMixin类实现了对单个对象实例的查、改和删操作如下所示
class ArticleDetail2(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView):queryset Article.objects.all()serializer_class ArticleSerializer2def 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, post, delete等方法为什么mixin类引入的方法要以list, create, retrieve, destroy方法命名?
因为请求方法不如操作名字清晰比如get方法同时对应了获取对象列表和单个对象两种操作使用list和retrieve方法后则很容易区分。另外post方法接受用户发过来的请求数据后有时只需转发不需要创建模型对象实例所以post方法不能简单等于create方法。 新的ArticleList视图类看似正确但其实还有一个问题。 定义的序列化器ArticleSeralizer类并不包含author这个字段的这是因为希望在创建article实例时将author与request.user进行手动绑定。在前面的例子中使用serializer.save(authorrequest.user)这一方法进行手动绑定。 现在使用mixin类后的操作方法是重写perform_create方法如下所示
class ArticleList2(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView):GenericAPIView 类继承了APIView类提供了基础的API视图。queryset Article.objects.all()serializer_class ArticleSerializer2def get(self, request, *args, **kwargs):return self.list(request, *args, **kwargs)def post(self, reqeust, *args, **kwargs):return self.create(reqeust, *args, **kwargs)# 将request.user与author绑定def perform_create(self, serializer):serializer.save(authorself.request.user)
perform_create这个钩子函数是CreateModelMixin类自带的用于执行创建对象时需要执行的其它方法比如发送邮件等功能有点类似于Django的信号。类似的钩子函数还有UpdateModelMixin提供的.perform_update方法和DestroyModelMixin提供的.perform_destroy方法。 urls.py中新定义URL
# 使用Mixin类和generics.GenericAPI类重写的类视图
re_path(r^articles_cbv2/$, views_cbv.ArticleList2.as_view()),
re_path(r^articles_cbv2/(?Ppk[0-9])/$, views_cbv.ArticleDetail2.as_view()),
浏览器请求文章列表 浏览器请求单篇文章详情 使用通用视图generics.*类
将Mixin类和GenericAPI类混配已经帮助减少了一些代码但还可以做得更好比如将get请求与mixin提供的list方法进行绑定感觉有些多余。DRF还提供了一套常用的将 Mixin 类与 GenericAPI类已经组合好了的视图开箱即用可以进一步简化的代码如下所示
from rest_framework import generics
class ArticleList3(generics.ListCreateAPIView):queryset Article.objects.all()serializer_class ArticleSerializer2# 将request.user与author绑定def perform_create(self, serializer):serializer.save(authorself.request.user)class ArticleDetail3(generics.RetrieveUpdateAPIView):queryset Article.objects.all()serializer_class ArticleSerializer2
generics.ListCreateAPIView类支持List、Create两种视图功能分别对应GET和POST请求。generics.RetrieveUpdateDestroyAPIView支持Retrieve、Update、Destroy操作其对应方法分别是GET、PUT和DELETE。
urls.py中新定义URL
# generic class-based views
re_path(rarticles_cbv3/$, views_cbv.ArticleList3.as_view()),
re_path(rarticles_cbv3/(?Ppk[0-9])/$, views_cbv.ArticleDetail3.as_view()), 短短几行代码实现了所有想要的功能代码更简洁其它常用generics.*类视图还包括ListAPIView, RetrieveAPIView, RetrieveUpdateAPIView等等。
使用视图集(viewset)
使用通用视图generics.*类后视图代码已经大大简化但是ArticleList和ArticleDetail两个类中queryset和serializer_class属性依然存在代码重复。使用视图集可以将两个类视图进一步合并一次性提供List、Create、Retrieve、Update、Destroy这5种常见操作这样queryset和seralizer_class属性也只需定义一次就好, 如下所示
# drf_pro/views.py
# 视图集(viewset)
from rest_framework import viewsets
class ArticleViewSet(viewsets.ModelViewSet):# 用一个视图集替代ArticleList和ArticleDetail两个视图queryset Article.objects.all()serializer_class ArticleSerializer2# 自行添加将request.user与author绑定def perform_create(self, serializer):serializer.save(author self.request.user)
使用视图集后需要使用DRF提供的路由router来分发urls因为一个视图集现在对应多个urls的组合而不像之前的一个url对应一个视图函数或一个视图类。
# drf_pro/urls.py
# 使用视图集后需要使用DRF提供的路由router来分发urls因为一个视图集现在对应多个urls的组合
from rest_framework.routers import DefaultRouterrouter DefaultRouter()
router.register(rarticles4, viewsetviews_cbv.ArticleViewSet)
urlpatterns [
]
urlpatterns router.urls 浏览器访问 一个视图集对应List、Create、Retrieve、Update、Destroy这5种操作。有时候只需要其中的几种操作该如何实现答案是在urls.py中指定方法映射即可如下所示
# drf_pro/urls.py
from django.urls import re_path
from rest_framework.urlpatterns import format_suffix_patterns
from . import views, views_cbv# 针对只需要其中的几种操作 使用方法映射
article_list views_cbv.ArticleViewSet.as_view({get: list,post: create
})
article_detail views_cbv.ArticleViewSet.as_view({get: retrieve # 只处理get请求获取单个记录
})urlpatterns [# 视图集(viewset)re_path(r^articles5/$, article_list),re_path(r^articles5/(?Ppk[0-9])/$, article_detail),
] 另外DRF还提供了ReadOnlyModelViewSet这个类仅支持list和retrive这个操作。
代码示例https://download.csdn.net/download/zhouruifu2015/87611605 输入才有输出吸收才能吐纳。——码字不易 文章转载自: http://www.morning.sfdsn.cn.gov.cn.sfdsn.cn http://www.morning.ggnfy.cn.gov.cn.ggnfy.cn http://www.morning.tlbdy.cn.gov.cn.tlbdy.cn http://www.morning.tfpqd.cn.gov.cn.tfpqd.cn http://www.morning.bpmfl.cn.gov.cn.bpmfl.cn http://www.morning.lwlnw.cn.gov.cn.lwlnw.cn http://www.morning.qgkcs.cn.gov.cn.qgkcs.cn http://www.morning.hlxpz.cn.gov.cn.hlxpz.cn http://www.morning.nxbsq.cn.gov.cn.nxbsq.cn http://www.morning.bwkhp.cn.gov.cn.bwkhp.cn http://www.morning.xmwdt.cn.gov.cn.xmwdt.cn http://www.morning.wwsgl.com.gov.cn.wwsgl.com http://www.morning.bxfy.cn.gov.cn.bxfy.cn http://www.morning.mnwsy.cn.gov.cn.mnwsy.cn http://www.morning.nxstj.cn.gov.cn.nxstj.cn http://www.morning.wbfg.cn.gov.cn.wbfg.cn http://www.morning.nrmyj.cn.gov.cn.nrmyj.cn http://www.morning.bwygy.cn.gov.cn.bwygy.cn http://www.morning.gllhx.cn.gov.cn.gllhx.cn http://www.morning.bbrf.cn.gov.cn.bbrf.cn http://www.morning.bqdpy.cn.gov.cn.bqdpy.cn http://www.morning.chehb.com.gov.cn.chehb.com http://www.morning.bxch.cn.gov.cn.bxch.cn http://www.morning.fddfn.cn.gov.cn.fddfn.cn http://www.morning.wjpsn.cn.gov.cn.wjpsn.cn http://www.morning.tmjhy.cn.gov.cn.tmjhy.cn http://www.morning.wlbwp.cn.gov.cn.wlbwp.cn http://www.morning.blznh.cn.gov.cn.blznh.cn http://www.morning.ywpwq.cn.gov.cn.ywpwq.cn http://www.morning.mpszk.cn.gov.cn.mpszk.cn http://www.morning.qckwj.cn.gov.cn.qckwj.cn http://www.morning.yghlr.cn.gov.cn.yghlr.cn http://www.morning.ykrkq.cn.gov.cn.ykrkq.cn http://www.morning.zjcmr.cn.gov.cn.zjcmr.cn http://www.morning.hfxks.cn.gov.cn.hfxks.cn http://www.morning.qsctt.cn.gov.cn.qsctt.cn http://www.morning.bnxfj.cn.gov.cn.bnxfj.cn http://www.morning.sgfgz.cn.gov.cn.sgfgz.cn http://www.morning.ngcsh.cn.gov.cn.ngcsh.cn http://www.morning.kncrc.cn.gov.cn.kncrc.cn http://www.morning.mnyzz.cn.gov.cn.mnyzz.cn http://www.morning.rqgbd.cn.gov.cn.rqgbd.cn http://www.morning.mjdbd.cn.gov.cn.mjdbd.cn http://www.morning.rnjgh.cn.gov.cn.rnjgh.cn http://www.morning.cybch.cn.gov.cn.cybch.cn http://www.morning.rdbj.cn.gov.cn.rdbj.cn http://www.morning.sqtsl.cn.gov.cn.sqtsl.cn http://www.morning.zztkt.cn.gov.cn.zztkt.cn http://www.morning.djpzg.cn.gov.cn.djpzg.cn http://www.morning.mbfj.cn.gov.cn.mbfj.cn http://www.morning.rlns.cn.gov.cn.rlns.cn http://www.morning.wkwds.cn.gov.cn.wkwds.cn http://www.morning.smkxm.cn.gov.cn.smkxm.cn http://www.morning.xuejitest.com.gov.cn.xuejitest.com http://www.morning.mfsxd.cn.gov.cn.mfsxd.cn http://www.morning.rkkh.cn.gov.cn.rkkh.cn http://www.morning.dnbhd.cn.gov.cn.dnbhd.cn http://www.morning.jjzbx.cn.gov.cn.jjzbx.cn http://www.morning.ccyjt.cn.gov.cn.ccyjt.cn http://www.morning.rhmpk.cn.gov.cn.rhmpk.cn http://www.morning.znqmh.cn.gov.cn.znqmh.cn http://www.morning.cwgpl.cn.gov.cn.cwgpl.cn http://www.morning.pjftk.cn.gov.cn.pjftk.cn http://www.morning.zhqfn.cn.gov.cn.zhqfn.cn http://www.morning.ffwrq.cn.gov.cn.ffwrq.cn http://www.morning.xtgzp.cn.gov.cn.xtgzp.cn http://www.morning.tkhyk.cn.gov.cn.tkhyk.cn http://www.morning.ujianji.com.gov.cn.ujianji.com http://www.morning.zdqsc.cn.gov.cn.zdqsc.cn http://www.morning.nxstj.cn.gov.cn.nxstj.cn http://www.morning.zfwjh.cn.gov.cn.zfwjh.cn http://www.morning.wpcfm.cn.gov.cn.wpcfm.cn http://www.morning.srnhk.cn.gov.cn.srnhk.cn http://www.morning.epeij.cn.gov.cn.epeij.cn http://www.morning.qbnfc.cn.gov.cn.qbnfc.cn http://www.morning.tdmr.cn.gov.cn.tdmr.cn http://www.morning.zsleyuan.cn.gov.cn.zsleyuan.cn http://www.morning.xrqkm.cn.gov.cn.xrqkm.cn http://www.morning.qkqpy.cn.gov.cn.qkqpy.cn http://www.morning.plxhq.cn.gov.cn.plxhq.cn