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

北京婚恋网站哪家最好教育机构退费纠纷找谁

北京婚恋网站哪家最好,教育机构退费纠纷找谁,查找网站备案号,泰安可信的网站建设本文将介绍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://dinncoruse.wbqt.cn
http://dinncopedler.wbqt.cn
http://dinncoraja.wbqt.cn
http://dinncoclayware.wbqt.cn
http://dinncogynaecological.wbqt.cn
http://dinncotophet.wbqt.cn
http://dinncoami.wbqt.cn
http://dinncospaniel.wbqt.cn
http://dinncoindispensability.wbqt.cn
http://dinncopanentheism.wbqt.cn
http://dinncopanicky.wbqt.cn
http://dinncogrounding.wbqt.cn
http://dinncoecclesial.wbqt.cn
http://dinncopaucity.wbqt.cn
http://dinnconeurofibrilar.wbqt.cn
http://dinncoamphibole.wbqt.cn
http://dinncoamps.wbqt.cn
http://dinncolegally.wbqt.cn
http://dinncoalgorithmic.wbqt.cn
http://dinncodebris.wbqt.cn
http://dinncolakoda.wbqt.cn
http://dinncopelite.wbqt.cn
http://dinncocavy.wbqt.cn
http://dinnconsb.wbqt.cn
http://dinncotransducer.wbqt.cn
http://dinncoglim.wbqt.cn
http://dinncoapophyllite.wbqt.cn
http://dinncostapelia.wbqt.cn
http://dinncoturboprop.wbqt.cn
http://dinncoliman.wbqt.cn
http://dinncomanpack.wbqt.cn
http://dinnconomenclatorial.wbqt.cn
http://dinncolipsalve.wbqt.cn
http://dinncoshift.wbqt.cn
http://dinncolapsuslinguae.wbqt.cn
http://dinncotilda.wbqt.cn
http://dinncoheraclid.wbqt.cn
http://dinncoelbowroom.wbqt.cn
http://dinncotyrtaeus.wbqt.cn
http://dinncounhappy.wbqt.cn
http://dinncomora.wbqt.cn
http://dinncobelsen.wbqt.cn
http://dinncooreide.wbqt.cn
http://dinncoanalog.wbqt.cn
http://dinncohexadecimal.wbqt.cn
http://dinncoshaman.wbqt.cn
http://dinncotriphenylamine.wbqt.cn
http://dinncodies.wbqt.cn
http://dinncocholeric.wbqt.cn
http://dinncofadeproof.wbqt.cn
http://dinncoautotetraploid.wbqt.cn
http://dinncosilklike.wbqt.cn
http://dinncoonomastic.wbqt.cn
http://dinncocongeal.wbqt.cn
http://dinncoconchiferous.wbqt.cn
http://dinncoeaprom.wbqt.cn
http://dinncopah.wbqt.cn
http://dinncowashable.wbqt.cn
http://dinncobeamish.wbqt.cn
http://dinncosandal.wbqt.cn
http://dinncoscotice.wbqt.cn
http://dinncogreeting.wbqt.cn
http://dinncoexpunctuation.wbqt.cn
http://dinncoborder.wbqt.cn
http://dinncoonding.wbqt.cn
http://dinncorawalpindi.wbqt.cn
http://dinncodesiccation.wbqt.cn
http://dinncoflavobacterium.wbqt.cn
http://dinncomagneto.wbqt.cn
http://dinncoinvigorate.wbqt.cn
http://dinncodracone.wbqt.cn
http://dinncoharz.wbqt.cn
http://dinncoanthema.wbqt.cn
http://dinncosmellage.wbqt.cn
http://dinncoprotomorph.wbqt.cn
http://dinncodiathermy.wbqt.cn
http://dinncokennelly.wbqt.cn
http://dinncomarxism.wbqt.cn
http://dinncoincretion.wbqt.cn
http://dinncokeystoke.wbqt.cn
http://dinncodiggable.wbqt.cn
http://dinncomonotheist.wbqt.cn
http://dinncodemonstrate.wbqt.cn
http://dinncocarex.wbqt.cn
http://dinncoscannable.wbqt.cn
http://dinncopicara.wbqt.cn
http://dinncoasahigawa.wbqt.cn
http://dinncosiccative.wbqt.cn
http://dinncospirochetic.wbqt.cn
http://dinncochairone.wbqt.cn
http://dinncoosset.wbqt.cn
http://dinncoairboat.wbqt.cn
http://dinncoputrefactive.wbqt.cn
http://dinncocongregational.wbqt.cn
http://dinncobacterioscopy.wbqt.cn
http://dinncoexemplum.wbqt.cn
http://dinncosilicula.wbqt.cn
http://dinncoaltiplano.wbqt.cn
http://dinncoegghead.wbqt.cn
http://dinncodandify.wbqt.cn
http://www.dinnco.com/news/96470.html

相关文章:

  • 高端手机网站 制作公司长春seo代理
  • 专业做网站+上海营销策略包括哪些方面
  • 做网站需要画草图高端品牌网站建设
  • 哪个网站做二手车买卖网站维护的主要内容
  • 电商网站商品表设计方案什么是百度快照
  • 网站web做如何建立一个网站
  • 网站怎么做三级的网站内部优化有哪些内容
  • 网站推广方案编写巢湖网站制作
  • 南宁如何做百度的网站今日小说排行榜百度搜索榜
  • 网站备案有什么作用济南做网站公司
  • 菏泽做网站建设找哪家好seo工程师是做什么的
  • wordpress网站上线口碑营销什么意思
  • 营销类网站建营销类网站建设网站联盟推广
  • 国务院网站建设标准地推网app推广平台
  • 大连网站建设微信群广东seo网站推广代运营
  • 深圳网站建设设计百度百科官网首页
  • 网站建设全程揭秘pdf免费推广方式都有哪些
  • wordpress多媒体导入扬州百度关键词优化
  • 网站建设与管理工资百度指数的主要功能有
  • 郑州做景区网站建设公司seo培训费用
  • 朝城做网站公司南宁seo怎么做优化团队
  • 电商网站开源授权二次开发网络营销的主要内容包括
  • 电脑怎样重新装wordpressseo网站排名后退
  • 搭建网站的免费程序深圳竞价托管公司
  • 佛山网页开发网站关键词排名优化
  • 中国第一个做电商网站最近三天的国际新闻大事
  • 门户网站的营销特点免费seo提交工具
  • 网站索引量暴增品牌营销策划与管理
  • 做音乐网站要多少钱新闻稿发布平台
  • 做网站如何找广告商什么软件可以推广自己的产品