DRF的序列化组件
rest
rest下的url
url唯一代表資源,http請(qǐng)求方式來區(qū)分用戶行為
url的設(shè)計(jì)規(guī)范
GET: 127.0.0.1:9001/books/ ? # 獲取所有數(shù)據(jù)
GET: 127.0.0.1:9001/books/{id} # 獲取單條數(shù)據(jù)
POST: 127.0.0.1:9001/books/ # 增加數(shù)據(jù)
DELETE: 127.0.0.1:9001/books/{id} ? # 刪除數(shù)據(jù)
PUT: 127.0.0.1:9001/books/{id} # 修改數(shù)據(jù)
數(shù)據(jù)響應(yīng)規(guī)范
GET: 127.0.0.1:9001/books/ ?? # 返回[{}, {}, {}]
GET: 127.0.0.1:9001/books/{id} # {} 單條數(shù)據(jù)
POST: 127.0.0.1:9001/books/ ? ?# {} 添加成功的數(shù)據(jù)
DELETE: 127.0.0.1:9001/books/{id} # "" 返回空
PUT: 127.0.0.1:9001/books/{id} # {} 更新后完整的數(shù)據(jù)
錯(cuò)誤處理
{ "error": "message" }
解析器組件
-
解析器組件是用來解析用戶請(qǐng)求的數(shù)據(jù)的(application/json), content-type
-
必須繼承APIView
-
request.data觸發(fā)解析
APIView的使用
rest_framework是一個(gè)app需要在settings里設(shè)置
INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','rest_framework', ]pip install djangorestframework
from rest_framework.views import APIView?
class LoginView(APIView):
def get(self, request):
pass
序列化組件
Django自帶的serializer
from django.serializers import serialize # 引入 ? origin_data = Book.objects.all() serialized_data = serialize("json", origin_data)DRF的序列化組件
接口設(shè)計(jì)
from rest_framework import serializers #引入創(chuàng)建一個(gè)序列化類
class BookSerializer(serializers.ModelSerializer):class Meta:model = Book# model字段fields = ('title','price','publish','authors','author_list','publish_name','publish_city')# 只需寫入不需要展示的字段extra_kwargs = {'publish': {'write_only': True},'authors': {'write_only': True}}# source為自定義需要展示的信息publish_name = serializers.CharField(max_length=32, read_only=True, source='publish.name')publish_city = serializers.CharField(max_length=32, read_only=True, source='publish.city')# 多對(duì)多字段需要自己手動(dòng)獲取數(shù)據(jù),SerializerMethodField()author_list = serializers.SerializerMethodField() ?def get_author_list(self, book_obj):# 拿到queryset開始循環(huán) [{}, {}, {}, {}]authors = list() ?for author in book_obj.authors.all():authors.append(author.name) ?return authors 創(chuàng)建序列化類開始序列化
get接口(查詢多條數(shù)據(jù)) & post接口
class BookView(APIView):def get(self, request):# 獲取querysetorigin_data = Book.objects.all()# 開始序列化serialized_data = BookSerializer(origin_data, many=True)return Response(serialized_data.data)def post(self, request):verified_data = BookSerializer(data=request.data)if verified_data.is_valid():book = verified_data.save()authors = Author.objects.filter(nid__in=request.data['authors'])book.authors.add(*authors)return Response(verified_data.data)else:return Response(verified_data.errors)get(查詢單條數(shù)據(jù)) & put接口 & delete接口
class BookFilterView(APIView):def get(self, request, nid):book_obj = Book.objects.get(pk=nid)serialized_data = BookSerializer(book_obj, many=False)return Response(serialized_data.data) ?def put(self, request, nid):book_obj = Book.objects.get(pk=nid)verified_data = BookSerializer(data=request.data, instance=book_obj)if verified_data.is_valid():verified_data.save()return Response(verified_data.data)else:return Response(verified_data.errors) ?def delete(self, request, nid):book_obj = Book.objects.get(pk=nid).delete()return Response()缺點(diǎn):
serializers.Serializer無法插入數(shù)據(jù),只能自己實(shí)現(xiàn)create字段太多,不能自動(dòng)序列化
接口設(shè)計(jì)優(yōu)化
使用視圖組件的mixin進(jìn)行接口邏輯優(yōu)化
導(dǎo)入mixin
from rest_framework.mixinx import (ListModelMix,CreateModelMixin,DestroyModelMixin,UpdateModelMixin,RetrieveModelMixin) from rest_framework.generics import GenericAPIView ?定義序列化類
Class BookSerializer(serializers.ModelSerializer):class Meta:Bookfields = ()...如上因?yàn)槭褂媚K化編程,建議將定義的序列化類放在單獨(dú)的模塊中,再在view.py中導(dǎo)入
from .app_serializers import BookSerializer定義視圖類?
class BookView(ListModelMix, CreateModelMixin, GenericAPIView):# queryset和serializer_class是固定的寫法queryset = Book.objects.all()serializer_class = BookSerializer def get():return self.list() # 查詢多條def post():return self.create()class BookFilterView(RetrieveModelMixin, DestroyModelMixin, UpdateModelMixin, GenericAPIView):queryset = Book.objects.all()serializer_class = BookSerializer ?def get():return self.retrieve() # 查詢單條 ?def delete():return self.destroy() ?def put():return self.update()注意:
查詢單挑數(shù)據(jù)的url需要給查詢的id進(jìn)行正則分組
re_path(r'books/(?P<pk>\d+)/$, views.BookFilterView.as_view())
使用視圖組件的view進(jìn)行接口邏輯優(yōu)化
導(dǎo)入模塊
from rest_framework import generics視圖類?
class BookView(generics.ListCreateAPIView)queryset = Book.objects.all()serializer_class = BookSerializer class BookFilterView(generics.RetrieveUpdateDestroyAPIView):queryset = Book.objects.all()serializer_class = BookSerializer使用視圖組件的viewset進(jìn)行接口邏輯優(yōu)化
導(dǎo)入模塊
from rest_framework.viewsets import ModelViewSet設(shè)計(jì)url
re_path(r'books/$, views.BookView.as_view({'get': 'list','post': 'create'})), re_path(r'books/(?P<pk>\d+)/$', views.BookView.as_view({'get': 'retrieve','delete': 'destroy','put': 'update'}))設(shè)計(jì)視圖類
class BookView(ModelViewSet):queryset = Book.objects.all()serializer_class = BookSerializer?
?
?
?
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/jiaqi-666/p/9416528.html
總結(jié)
- 上一篇: 腾讯QQ卡住提示未响应解决方法
- 下一篇: SpringBoot实战(五)之Thym