当前位置: 首页 > news >正文

企业专业网站建设的必要性b2b电子商务网站都有哪些

企业专业网站建设的必要性,b2b电子商务网站都有哪些,wordpress修改仪表盘,怎么做网页excel本文将介绍django视图集的内部实现,并带你重写部分代码自己组装强大且趁手的视图集,以满足自定义的业务需求,避免编写大量重复代码。 一、基础知识 Django Rest framework框架允许你将一组相关视图的逻辑组合到一个类中,也就是我…

本文将介绍django视图集的内部实现,并带你重写部分代码自己组装强大且趁手的视图集,以满足自定义的业务需求,避免编写大量重复代码。

一、基础知识

Django Rest framework框架允许你将一组相关视图的逻辑组合到一个类中,也就是我们所谓的视图集ViewSet

APIView相比,ViewSet更加抽象,更难理解。APIView的使用方法非常直观,需要你提供诸如.get().post()之类的处理方法,并由其自动将请求分发到对应的方法上。ViewSet则不同,它要求你提供诸如.list().create()这类操作方法,在实现了这些方法之后,使用.as_view()方法请操作方法映射到不同的处理方法上,比如list->getdestroy->delete

一个简单的示例

from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
from myapps.serializers import UserSerializer
from rest_framework import viewsets
from rest_framework.response import Responseclass UserViewSet(viewsets.ViewSet):"""一个简单的视图集,实现获取用户列表和查询单个用户的功能"""def list(self, request):queryset = User.objects.all()serializer = UserSerializer(queryset, many=True)return Response(serializer.data)def retrieve(self, request, pk=None):queryset = User.objects.all()user = get_object_or_404(queryset, pk=pk)serializer = UserSerializer(user)return Response(serializer.data)

在很多普通业务中,增删改查的操作是相同的,比如请求数据列表的操作,无非是三步:数据库获取查询集->序列化->返回响应。drf预制了这些重复的工作,将通用的方法封装进了ModelViewSet,借助ModelViewSet我们可以非常轻松的完成增删改查等工作(对应APIView就是ModelAPIView):

class AccountViewSet(viewsets.ModelViewSet):"""只需要指定查询集和序列化器即可"""queryset = Account.objects.all()serializer_class = AccountSerializerpermission_classes = [IsAccountAdminOrReadOnly]

ModelViewSet本身不提供这些通用的listcreate之类的方法,而是由一些列Mixin类来实现,ModelViewSet负责把它们组合起来:

class ModelViewSet(mixins.CreateModelMixin,mixins.RetrieveModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin,mixins.ListModelMixin,GenericViewSet):    pass

就以CreateModelMixin为例,CreateModelMixin为我们提供了一个通用的和符合标准的create()方法,其过程也就是获取查询集->序列化->返回,没有特殊需求我们的视图集继承它就能获取预制的create方法,不需要再自己实现:

class CreateModelMixin:"""Create a model instance."""def create(self, request, *args, **kwargs):serializer = self.get_serializer(data=request.data)serializer.is_valid(raise_exception=True)self.perform_create(serializer)headers = self.get_success_headers(serializer.data)return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)def perform_create(self, serializer):serializer.save()def get_success_headers(self, data):try:return {'Location': str(data[api_settings.URL_FIELD_NAME])}except (TypeError, KeyError):return {}

细心观察在CreateModelMixin中我们获取序列化器的方法是get_serializer,此外一些其它的Minxin类中,你可能发现其获取查询集的方法是get_queryset或者filter_queryset,还有诸如paginate_queryset这样的方法,一个典型的示例就是ListModelMixin:

class ListModelMixin:"""List a queryset."""def list(self, request, *args, **kwargs):queryset = self.filter_queryset(self.get_queryset())page = self.paginate_queryset(queryset)if page is not None:serializer = self.get_serializer(page, many=True)return self.get_paginated_response(serializer.data)serializer = self.get_serializer(queryset, many=True)return Response(serializer.data)

这些方法并非凭空而来而是由GenericViewSet类来提供,准确说是它的父类GenericAPIView

class GenericViewSet(ViewSetMixin, generics.GenericAPIView):    pass

GenericViewSet继承GenericAPIView为各种Mixin提供统一的获取查询集、序列化器、分页、授权等等接口。

class GenericAPIView(views.APIView):...queryset = Noneserializer_class = None...def get_queryset(self):...def get_object(self):...def get_serializer(self, *args, **kwargs):...def get_serializer_class(self):...def get_serializer_context(self):...def filter_queryset(self, queryset):...def paginator(self):...def paginate_queryset(self, queryset):...def get_paginated_response(self, data):...

二、灵活自定义

drf预制的Mixin足够标准和通用,但如果我们的业务中有特殊需求,我们就需要对drf预制的Mixin重新烹饪,实际操作并不困难,接下来我们通过几个具体的场景来实际体会一下。

自定义响应格式

假如我想让视图集返回的响应遵循如下格式:

{"status": "ok","code": 200,"messages": [],"result": {"user": {"id": 123,"name": "shazow"}}
}

我们可以先实现一个自定义的响应类来替换掉Mixin中使用的响应类。

import json
from rest_framework.response import Responseclass Rep(Response):"""struct json response"""def __init__(self, result=None, message=None, status=None, code=None, **kwargs):if message is None:message = []data = {"status": status,"code": code,"message": message,"result": result}super().__init__(data, code, **kwargs)@staticmethoddef ok(result=None, message=None, code=None, **kwargs):return Rep(result=result, message=message, status="ok", code=code, **kwargs)@staticmethoddef err(result=None, message=None, code=None, **kwargs):return Rep(result=result, message=message, status="err", code=code, **kwargs)

RetrieveModelMixin为例,你可以继承并重写retrieve,也可以干脆复制一份到自己的项目中,再修改retrieve方法,我们这里选择复制一份到自己的项目中。为了和原来的RetrieveModelMixin做区分,且将其命名为XRetrieveModelMixin:

class XRetrieveModelMixin:"""Retrieve a model instance."""# 使用我们自己的Rep响应类替换了Response响应类def retrieve(self, request, *args, **kwargs):try:instance = self.get_object()except Http404:return Rep.err(None, ["查询数据不存在"], status.HTTP_404_NOT_FOUND)serializer = self.get_serializer(instance)return Rep.ok(serializer.data, None, code=status.HTTP_200_OK)# 对比原来的
# class RetrieveModelMixin:
#     """
#     Retrieve a model instance.
#     """
#     def retrieve(self, request, *args, **kwargs):
#         instance = self.get_object()
#         serializer = self.get_serializer(instance)
#         return Response(serializer.data)

自动记录创建和更新数据的用户

细心观察drf的Minxin类并不是将全部分逻辑写在一个create方法或者update方法中,实际上它把实现功能的代码拆分到了多个函数中。

CreateModelMixin类为例,你可以看到create的方法由perform_create方法和get_success_headers组合而来:

class CreateModelMixin:"""Create a model instance."""def create(self, request, *args, **kwargs):serializer = self.get_serializer(data=request.data)serializer.is_valid(raise_exception=True)self.perform_create(serializer)headers = self.get_success_headers(serializer.data)return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)def perform_create(self, serializer):serializer.save()def get_success_headers(self, data):try:return {'Location': str(data[api_settings.URL_FIELD_NAME])}except (TypeError, KeyError):return {}

这样非常有利于我们进行重写,假如我们想对serializer.save()的过程做些修改,比如记录创建用户,我们就可以通过重写perform_create来实现:

class TrackerModelViewSet(ModelViewSet):def perform_create(self, serializer):serializer.save(created_by=self.request.user)# 记录更新操作的用户;perform_update来自UpdateModelMixindef perform_update(self, serializer):serializer.save(updated_by=self.request.user)

三、总结

学习drf是如何预制Mixin的,我们可以预制自己的Mixin类和视图集,运用得当我们可以打造属于自己的趁手工具以从大量重复工作中解脱。


文章转载自:
http://orthros.wghp.cn
http://nabe.wghp.cn
http://howsoever.wghp.cn
http://cleanlily.wghp.cn
http://intermittence.wghp.cn
http://pouter.wghp.cn
http://slinkweed.wghp.cn
http://binding.wghp.cn
http://misdoubt.wghp.cn
http://transire.wghp.cn
http://furmety.wghp.cn
http://electrolyse.wghp.cn
http://halobiotic.wghp.cn
http://lyriform.wghp.cn
http://oregonian.wghp.cn
http://contraoctave.wghp.cn
http://viagraph.wghp.cn
http://oddfellow.wghp.cn
http://integrodifferential.wghp.cn
http://hydroxyl.wghp.cn
http://kama.wghp.cn
http://lexigraphy.wghp.cn
http://photogun.wghp.cn
http://cytogenetically.wghp.cn
http://housewifely.wghp.cn
http://tabby.wghp.cn
http://ornithomancy.wghp.cn
http://ambush.wghp.cn
http://lexica.wghp.cn
http://posteriority.wghp.cn
http://blarney.wghp.cn
http://meerschaum.wghp.cn
http://manama.wghp.cn
http://odorously.wghp.cn
http://causable.wghp.cn
http://contestable.wghp.cn
http://inspectorship.wghp.cn
http://handbill.wghp.cn
http://leda.wghp.cn
http://manicurist.wghp.cn
http://riven.wghp.cn
http://choreal.wghp.cn
http://probable.wghp.cn
http://diamantiferous.wghp.cn
http://hypopsychosis.wghp.cn
http://dirham.wghp.cn
http://waterborne.wghp.cn
http://dnis.wghp.cn
http://psammon.wghp.cn
http://capacitivity.wghp.cn
http://underrepresentation.wghp.cn
http://dustman.wghp.cn
http://perineum.wghp.cn
http://thankfully.wghp.cn
http://untwine.wghp.cn
http://bok.wghp.cn
http://stull.wghp.cn
http://posttraumatic.wghp.cn
http://immerse.wghp.cn
http://copestone.wghp.cn
http://nasal.wghp.cn
http://undeniable.wghp.cn
http://betweenness.wghp.cn
http://unclassified.wghp.cn
http://epiblast.wghp.cn
http://hatting.wghp.cn
http://keos.wghp.cn
http://triecious.wghp.cn
http://stucco.wghp.cn
http://cairo.wghp.cn
http://vexil.wghp.cn
http://plowshoe.wghp.cn
http://topdressing.wghp.cn
http://debrecen.wghp.cn
http://entitle.wghp.cn
http://instructively.wghp.cn
http://ibizan.wghp.cn
http://disimmure.wghp.cn
http://unauthoritative.wghp.cn
http://wrinkle.wghp.cn
http://anolyte.wghp.cn
http://schismatist.wghp.cn
http://manshift.wghp.cn
http://homogametic.wghp.cn
http://understrength.wghp.cn
http://carbanion.wghp.cn
http://parish.wghp.cn
http://raspberry.wghp.cn
http://extrusion.wghp.cn
http://desperation.wghp.cn
http://tilak.wghp.cn
http://conrail.wghp.cn
http://apiarian.wghp.cn
http://intellect.wghp.cn
http://inerrant.wghp.cn
http://waterish.wghp.cn
http://bennery.wghp.cn
http://pragmatize.wghp.cn
http://haemophile.wghp.cn
http://vicissitude.wghp.cn
http://www.hrbkazy.com/news/65609.html

相关文章:

  • qq推广链接乐陵seo外包
  • 湖南省人民政府驻深圳办事处aso优化费用
  • 没注册可以做网站吗企业微信scrm
  • 无锡市疫情最新消息外链seo推广
  • 客户crm管理系统北京百度seo价格
  • html5 手机网站开发叫才seo广告优化多少钱
  • 闵行网站建设简述seo的基本步骤
  • 网站评论回复如何做百度推广代理开户
  • 昆明做网站优化公司需要一个网站
  • 广州网站建设哪里好seo优化培训多少钱
  • 手机网址大全哪个好厦门seo网络优化公司
  • 在百度云上建设网站指数函数和对数函数
  • 自己做的主页网站怕被劫持深圳网络营销
  • web响应式设计 那些网站企业百度推广
  • 用phpmysql做网站国内网络推广渠道
  • 网站在线订单系统怎么做网站推广建设
  • 石家庄做公司网站线上宣传方案
  • 上海建设工程信息服务平台东莞关键词排名优化
  • 网站seo描述优化科技
  • 做网站前景百度推广网站平台
  • 怎么修改网站信息成都seo专家
  • 那个网站做调查问卷能赚钱seo网站优化价格
  • 衢州做外贸网站的公司新闻营销发稿平台
  • 高端集团网站建设企业推广网络营销外包服务
  • 宿迁网站建设开发五种营销工具
  • 网站建设模板坏处win10优化工具下载
  • 怎么做移动端网站最新的新闻 最新消息
  • 网站开发验收流程免费开店的电商平台
  • 响应式网站用什么语言网络视频营销
  • 最好wordpress积分付费插件seo网站seo