這篇文章給大家分享的是有關(guān)django基于restframework的CBV封裝怎么實現(xiàn)的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
站在用戶的角度思考問題,與客戶深入溝通,找到楊浦網(wǎng)站設(shè)計與楊浦網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗,讓設(shè)計與互聯(lián)網(wǎng)技術(shù)結(jié)合,創(chuàng)造個性化、用戶體驗好的作品,建站類型包括:成都做網(wǎng)站、網(wǎng)站設(shè)計、企業(yè)官網(wǎng)、英文網(wǎng)站、手機端網(wǎng)站、網(wǎng)站推廣、域名注冊、雅安服務(wù)器托管、企業(yè)郵箱。業(yè)務(wù)覆蓋楊浦地區(qū)。from django.db import models # Create your models here. class Book(models.Model): title=models.CharField(max_length=32) price=models.IntegerField() pub_date=models.DateField() publish=models.ForeignKey(to="Publish") authors=models.ManyToManyField(to="Author") def __str__(self): return self.title class Publish(models.Model): name=models.CharField(max_length=32) email=models.EmailField() def __str__(self): return self.name class Author(models.Model): name=models.CharField(max_length=32) age=models.IntegerField() def __str__(self): return self.name
from rest_framework import serializers from app01 import models from rest_framework import exceptions class BookSerialize(serializers.ModelSerializer): class Meta: model = models.Book fields = "__all__" publish = serializers.SerializerMethodField() authors = serializers.SerializerMethodField() def get_publish(self, obj): return {"publish_id": obj.publish.pk, "publish_name": obj.publish.name} def get_authors(self, obj): author_list = obj.authors.all() lis = [{"name": author.name, "age": author.age} for author in author_list] return lis def validate_title(self, value): if value.startswith("sb"): raise exceptions.ValidationError('你使用了不合適的文字') return value
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.Books.as_view()), ]
主要就是將CBV的幾個get,post請求方法進行封裝,以后創(chuàng)建其他的新的CBV,直接繼承調(diào)用就可以了,可以減少代碼冗余
from app01 import models from rest_framework.response import Response from rest_framework.views import APIView from app01.serialize_module import BookSerialize # 自定義一個response類,方便CBV使用 class MyResponse(): def __init__(self): self.status = 100 self.msg = None # 將類方法裝飾成屬性 @property def get_dic(self): return self.__dict__ # 封裝CBV類 # 將get請求封裝在List類中 class List(): def get_list(self, request,*args,**kwargs): response = MyResponse() try: handler_list = self.model.objects.all() handler_ser = self.serializer(instance=handler_list, many=True) response.handler = handler_ser.data response.msg = "獲取成功" except Exception as e: response.msg="獲取失敗" response.error=str(e) return Response(response.get_dic) # 將post請求封裝在Create類中 class Create(): def save(self, request,*args,**kwargs): response = MyResponse() try: handler_ser = self.serializer(data=request.data) if handler_ser.is_valid(): handler_ser.save() response.msg = "添加成功" else: response.status = 101 response.msg = "添加失敗" response.error = handler_ser.errors except Exception as e: response.msg = "添加失敗" response.error=str(e) return Response(response.get_dic) # book類繼承List,Create,APIView class Books(List,Create,APIView): model=models.Book serializer=BookSerialize # 此時調(diào)用get方法時,只要使用List類中的get_list方法就行了 def get(self,request): return self.get_list(request) # 此時調(diào)用post方法時,只要使用Create類中的save方法就行了 def post(self,request): return self.save(request)
感謝各位的閱讀!關(guān)于“django基于restframework的CBV封裝怎么實現(xiàn)”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機、免備案服務(wù)器”等云主機租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。