一 面向資源編程
每個(gè)URL代表一種資源,URL中盡量不要用動詞,要用名詞。
二 根據(jù)method不同,進(jìn)行不同的操作
GET/POST/PUT/DELETE/PATCH
三 在URL中體現(xiàn)版本
https://www.bootcss.com/v1/mycss
https://v1.bootcss.com/mycss
四 在URL中體現(xiàn)是否是API
https://www.bootcss.com/api/mycss
https://api.bootcss.com/mycss
五 在URL中的過濾條件
https://www.bootcss.com/v1/mycss?page=3
六 盡量使用HTTPS
https://www.bootcss.com/v1/mycss
七 響應(yīng)時(shí)設(shè)置狀態(tài)碼
1** 信息,服務(wù)器收到請求,需要請求者繼續(xù)執(zhí)行操作
2** 成功,操作被成功接收并處理
3** 重定向,需要進(jìn)一步的操作以完成請求
4** 客戶端錯(cuò)誤,請求包含語法錯(cuò)誤或無法完成請求
5** 服務(wù)器錯(cuò)誤,服務(wù)器在處理請求的過程中發(fā)生了錯(cuò)誤
八 返回值
GET請求 返回查到所有或單條數(shù)據(jù)
POST請求 返回新增的數(shù)據(jù)
PUT請求 返回更新數(shù)據(jù)
PATCH請求 局部更新 返回更新整條數(shù)據(jù)
DELETE請求 返回值為空
九 返回錯(cuò)誤信息
返回值攜帶錯(cuò)誤信息
十 Hypermedia API
如果遇到需要跳轉(zhuǎn)的情況 攜帶跳轉(zhuǎn)接口的URL
ret = {
code: 1000,
data:{
id:1,
name:'小強(qiáng)',
depart_id:http://www.luffycity.com/api/v1/depart/8/
}
}
當(dāng)我們做前后端分離的項(xiàng)目~~我們前后端交互一般都選擇JSON數(shù)據(jù)格式,JSON是一個(gè)輕量級的數(shù)據(jù)交互格式。
那么我們給前端數(shù)據(jù)的時(shí)候都要轉(zhuǎn)成json格式,那就需要對我們從數(shù)據(jù)庫拿到的數(shù)據(jù)進(jìn)行序列化。
接下來我們看下django序列化和rest_framework序列化的對比~~
#1.Jsonresponse序列化方式
class BooksView(View):
def get(self, request):
book_list = Book.objects.values("id", "title", "chapter", "pub_time", "publisher")
book_list = list(book_list)
# 如果我們需要取外鍵關(guān)聯(lián)的字段信息 需要循環(huán)獲取外鍵 再去數(shù)據(jù)庫查然后拼接成我們想要的
ret = []
for book in book_list:
pub_dict = {}
pub_obj = Publish.objects.filter(pk=book["publisher"]).first()
pub_dict["id"] = pub_obj.pk
pub_dict["title"] = pub_obj.title
book["publisher"] = pub_dict
ret.append(book)
ret = json.dumps(book_list, ensure_ascii=False, cls=MyJson)
return HttpResponse(ret)
# json.JSONEncoder.default()
# 解決json不能序列化時(shí)間字段的問題
class MyJson(json.JSONEncoder):
def default(self, field):
if isinstance(field, datetime.datetime):
return field.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(field, datetime.date):
return field.strftime('%Y-%m-%d')
else:
return json.JSONEncoder.default(self, field)
#2.Django序列化方法
from django.core import serializers
# 能夠得到我們要的效果 結(jié)構(gòu)有點(diǎn)復(fù)雜
class BooksView(View):
def get(self, request):
book_list = Book.objects.all()
ret = serializers.serialize("json", book_list)
return HttpResponse(ret)
-- Django我們CBV繼承類是View,現(xiàn)在DRF我們要用APIView
-- Django中返回的時(shí)候我們用HTTPResponse,JsonResponse,render ,DRF我們用Response
from rest_framework import serializers
class BookSerializer(serializers.Serializer):
id = serializers.IntegerField()
title = serializers.CharField(max_length=32)
CHOICES = ((1, "Linux"), (2, "Django"), (3, "Python"))
# 這是為了顯示choice字段的值
chapter = serializers.ChoiceField(choices=CHOICES, source="get_category_display")
pub_time = serializers.DateField()
from rest_framework.views import APIView
from rest_framework.response import Response
from app.models import Book, Publisher
from app.serializers import BookSerializer
class BookView(APIView):
def get(self, request):
book_list = Book.objects.all()
ret = BookSerializer(book_list, many=True)
return Response(ret.data)
建網(wǎng)站原本是網(wǎng)站策劃師、網(wǎng)絡(luò)程序員、網(wǎng)頁設(shè)計(jì)師等,應(yīng)用各種網(wǎng)絡(luò)程序開發(fā)技術(shù)和網(wǎng)頁設(shè)計(jì)技術(shù)配合操作的協(xié)同工作。成都創(chuàng)新互聯(lián)專業(yè)提供網(wǎng)站建設(shè)、網(wǎng)站設(shè)計(jì),網(wǎng)頁設(shè)計(jì),網(wǎng)站制作(企業(yè)站、響應(yīng)式網(wǎng)站建設(shè)、電商門戶網(wǎng)站)等服務(wù),從網(wǎng)站深度策劃、搜索引擎友好度優(yōu)化到用戶體驗(yàn)的提升,我們力求做到極致!#serialisers.py
from django.db import models
# Create your models here.
__all__ = ["Book", "Publisher", "Author"]
class Book(models.Model):
title = models.CharField(max_length=32, verbose_name="圖書名稱")
CHOICES = ((1, "Python"), (2, "Go"), (3, "Linux"))
category = models.IntegerField(choices=CHOICES, verbose_name="圖書的類別")
pub_time = models.DateField(verbose_name="圖書的出版日期")
publisher = models.ForeignKey(to="Publisher", on_delete=None)
author = models.ManyToManyField(to="Author")
def __str__(self):
return self.title
class Meta:
verbose_name_plural = "book"
class Publisher(models.Model):
title = models.CharField(max_length=32, verbose_name="出版社的名稱")
def __str__(self):
return self.title
class Meta:
verbose_name_plural = "publish"
class Author(models.Model):
name = models.CharField(max_length=32, verbose_name="作者的姓名")
def __str__(self):
return self.name
class Meta:
verbose_name_plural = "author"
#views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from app.models import Book, Publisher
from app.serializers import BookSerializer
class BookView(APIView):
def get(self, request):
book_list = Book.objects.all()
ret = BookSerializer(book_list, many=True)
return Response(ret.data)
當(dāng)前端給我們發(fā)post的請求的時(shí)候~前端給我們傳過來的數(shù)據(jù)~我們要進(jìn)行一些校驗(yàn)然后保存到數(shù)據(jù)庫~
這些校驗(yàn)以及保存工作,DRF的Serializer也給我們提供了一些方法了~~
首先~我們要寫反序列化用的一些字段~有些字段要跟序列化區(qū)分開~
Serializer提供了.is_valid() 和.save()方法~~
使用write_only=True,read_only=True區(qū)別序列化字段和反序列化字段
必須重寫create方法
from rest_framework import serializers
from .models import Book
class PublisherSerializer(serializers.Serializer):
id = serializers.IntegerField()
title = serializers.CharField(max_length=32)
class AuthorSerializer(serializers.Serializer):
id = serializers.IntegerField()
name = serializers.CharField(max_length=32)
book_obj = {
"title": "vita的使用教程",
"w_category": 1,
"pub_time": "2018-10-09",
"publisher_id": 1,
"author_list": [1, 2]
}
class BookSerializer(serializers.Serializer):
# 插入數(shù)據(jù)時(shí)id自動生成,不需要校驗(yàn)
id = serializers.IntegerField(required=False)
title = serializers.CharField(max_length=32)
CHOICES = ((1, "Python"), (2, "Go"), (3, "Linux"))
# read_only=True只在序列化的時(shí)候使用
category = serializers.ChoiceField(choices=CHOICES, source="get_category_display", read_only=True)
pub_time = serializers.DateField()
# write_only=True反序列化的字段,只在反序列化的時(shí)候使用,即保存數(shù)據(jù)的時(shí)候使用
w_category = serializers.ChoiceField(choices=CHOICES, write_only=True)
# 只在反序列化的時(shí)候使用,插入數(shù)據(jù)的時(shí)候,只需要插入publisher_id就可以了
publisher_id = serializers.IntegerField(write_only=True)
# 一定要加上read_only=True,否則在插入數(shù)據(jù)的時(shí)候,提示該字段必須添加
publisher = PublisherSerializer(read_only=True)
# 指明是多對多的外鍵關(guān)系
author = AuthorSerializer(many=True, read_only=True)
# 同樣,只在反序列化,保存數(shù)據(jù)的時(shí)候使用
author_list = serializers.ListField(write_only=True)
def create(self, validated_data):
"""
反序列化的時(shí)候,一定要寫create方法
:param validated_data:
:return:
"""
book = Book.objects.create(title=validated_data["title"], category=validated_data["w_category"],
pub_time=validated_data["pub_time"], publisher_id=validated_data["publisher_id"])
# 多對多的創(chuàng)建
book.author.add(*validated_data["author_list"])
return book
#views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from app.models import Book, Publisher
from app.serializers import BookSerializer
class BookView(APIView):
def get(self, request):
book_list = Book.objects.all()
ret = BookSerializer(book_list, many=True)
return Response(ret.data)
def post(self, request):
"""
反序列化,保存數(shù)據(jù)
:param request:
:return:
"""
print(request.data)
serializer = BookSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:
return Response(serializer.errors)
#urls.py
from django.contrib import admin
from django.urls import path,include
from app.views import BookView,BookEditView
urlpatterns = [
path('admin/', admin.site.urls),
path('list', BookView.as_view()),
path('retrieve/', BookEditView.as_view()),
]
#views.py
class BookEditView(APIView):
def get(self, request, id):
"""
獲取單條數(shù)據(jù)的接口
:param request:
:param id:
:return:
"""
book_obj = Book.objects.filter(id=id).first()
ret = BookSerializer(book_obj)
return Response(ret.data)
# views.py
class BookEditView(APIView):
def get(self, request, id):
"""
獲取單條數(shù)據(jù)的接口
:param request:
:param id:
:return:
"""
book_obj = Book.objects.filter(id=id).first()
ret = BookSerializer(book_obj)
return Response(ret.data)
def put(self, request, id):
"""
用戶提交Put請求
:param request:
:param id:
:return:
"""
book_obj = Book.objects.filter(id=id).first()
# partial=True允許部分校驗(yàn)
serializer = BookSerializer(book_obj, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:
return Response(serializer.errors)
from rest_framework import serializers
from .models import Book
class PublisherSerializer(serializers.Serializer):
id = serializers.IntegerField()
title = serializers.CharField(max_length=32)
class AuthorSerializer(serializers.Serializer):
id = serializers.IntegerField()
name = serializers.CharField(max_length=32)
book_obj = {
"title": "vita的使用教程",
"w_category": 1,
"pub_time": "2018-10-09",
"publisher_id": 1,
"author_list": [1, 2]
}
put_data = {
"title": "vita的使用教程2"
}
class BookSerializer(serializers.Serializer):
# 插入數(shù)據(jù)時(shí)id自動生成,不需要校驗(yàn)
id = serializers.IntegerField(required=False)
title = serializers.CharField(max_length=32)
CHOICES = ((1, "Python"), (2, "Go"), (3, "Linux"))
# read_only=True只在序列化的時(shí)候使用
category = serializers.ChoiceField(choices=CHOICES, source="get_category_display", read_only=True)
pub_time = serializers.DateField()
# write_only=True反序列化的字段,只在反序列化的時(shí)候使用,即保存數(shù)據(jù)的時(shí)候使用
w_category = serializers.ChoiceField(choices=CHOICES, write_only=True)
# 只在反序列化的時(shí)候使用,插入數(shù)據(jù)的時(shí)候,只需要插入publisher_id就可以了
publisher_id = serializers.IntegerField(write_only=True)
# 一定要加上read_only=True,否則在插入數(shù)據(jù)的時(shí)候,提示該字段必須添加
publisher = PublisherSerializer(read_only=True)
# 指明是多對多的外鍵關(guān)系
author = AuthorSerializer(many=True, read_only=True)
# 同樣,只在反序列化,保存數(shù)據(jù)的時(shí)候使用
author_list = serializers.ListField(write_only=True)
def create(self, validated_data):
"""
反序列化的時(shí)候,一定要寫create方法
:param validated_data:
:return:
"""
book = Book.objects.create(title=validated_data["title"], category=validated_data["w_category"],
pub_time=validated_data["pub_time"], publisher_id=validated_data["publisher_id"])
# 多對多的創(chuàng)建
book.author.add(*validated_data["author_list"])
return book
def update(self, instance, validated_data):
"""
Put請求的方法
:param instance:
:param validated_data:
:return:
"""
#如果該字段沒有,就使用原來的數(shù)據(jù)
instance.title = validated_data.get("title", instance.title)
instance.category = validated_data.get("category", instance.category)
instance.pub_time = validated_data.get("pub_time", instance.pub_time)
instance.publisher_id = validated_data.get("publisher_id", instance.publisher_id)
# 多對多的處理,如果用戶傳了該字段,就更新
if validated_data.get("author_list"):
instance.author.set(validated_data["author_list"])
instance.save()
return instance
def my_validate(value):
"""
全局驗(yàn)證
:param value:
:return:
"""
if "敏感信息" in value.lower():
raise serializers.ValidationError("不能含有敏感信息")
else:
return value
class BookSerializer(serializers.Serializer):
# 插入數(shù)據(jù)時(shí)id自動生成,不需要校驗(yàn)
id = serializers.IntegerField(required=False)
title = serializers.CharField(max_length=32, validators=[my_validate])
CHOICES = ((1, "Python"), (2, "Go"), (3, "Linux"))
# read_only=True只在序列化的時(shí)候使用
category = serializers.ChoiceField(choices=CHOICES, source="get_category_display", read_only=True)
pub_time = serializers.DateField()
# write_only=True反序列化的字段,只在反序列化的時(shí)候使用,即保存數(shù)據(jù)的時(shí)候使用
w_category = serializers.ChoiceField(choices=CHOICES, write_only=True)
# 只在反序列化的時(shí)候使用,插入數(shù)據(jù)的時(shí)候,只需要插入publisher_id就可以了
publisher_id = serializers.IntegerField(write_only=True)
# 一定要加上read_only=True,否則在插入數(shù)據(jù)的時(shí)候,提示該字段必須添加
publisher = PublisherSerializer(read_only=True)
# 指明是多對多的外鍵關(guān)系
author = AuthorSerializer(many=True, read_only=True)
# 同樣,只在反序列化,保存數(shù)據(jù)的時(shí)候使用
author_list = serializers.ListField(write_only=True)
def create(self, validated_data):
"""
反序列化的時(shí)候,一定要寫create方法
:param validated_data:
:return:
"""
book = Book.objects.create(title=validated_data["title"], category=validated_data["w_category"],
pub_time=validated_data["pub_time"], publisher_id=validated_data["publisher_id"])
# 多對多的創(chuàng)建
book.author.add(*validated_data["author_list"])
return book
def update(self, instance, validated_data):
"""
Put請求的方法
:param instance:
:param validated_data:
:return:
"""
#如果該字段沒有,就使用原來的數(shù)據(jù)
instance.title = validated_data.get("title", instance.title)
instance.category = validated_data.get("category", instance.category)
instance.pub_time = validated_data.get("pub_time", instance.pub_time)
instance.publisher_id = validated_data.get("publisher_id", instance.publisher_id)
# 多對多的處理,如果用戶傳了該字段,就更新
if validated_data.get("author_list"):
instance.author.set(validated_data["author_list"])
instance.save()
return instance
def validate_title(self, value):
"""
單個(gè)字段的驗(yàn)證
:param value:
:return:
"""
if "python" not in value.lower():
raise serializers.ValidationError("標(biāo)題必須含有python")
return value
def validate(self, attrs):
"""
多個(gè)字段的驗(yàn)證
:param attrs:
:return:
"""
if attrs["w_category"] == 1 and attrs["publisher_id"] == 1:
return attrs
else:
raise serializers.ValidationError("分類以及標(biāo)題不符合要求")
現(xiàn)在我們已經(jīng)清楚了Serializer的用法,會發(fā)現(xiàn)我們所有的序列化跟我們的模型都緊密相關(guān)~
那么,DRF也給我們提供了跟模型緊密相關(guān)的序列化器~~ModelSerializer~~
-- 它會根據(jù)模型自動生成一組字段
-- 它簡單的默認(rèn)實(shí)現(xiàn)了.update()以及.create()方法
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = "__all__"
# fields = ["id", "title", "pub_time"]
# exclude = ["user"]
# 分別是所有字段 包含某些字段 排除某些字段
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = "__all__"
# fields = ["id", "title", "pub_time"]
# exclude = ["user"]
# 分別是所有字段 包含某些字段 排除某些字段
depth = 1
# depth 代表找嵌套關(guān)系的第幾層
我們可以聲明一些字段來覆蓋默認(rèn)字段,來進(jìn)行自定制~
比如我們的選擇字段,默認(rèn)顯示的是選擇的key,我們要給用戶展示的是value。
class BookSerializer(serializers.ModelSerializer):
chapter = serializers.CharField(source="get_chapter_display", read_only=True)
class Meta:
model = Book
fields = "__all__"
# fields = ["id", "title", "pub_time"]
# exclude = ["user"]
# 分別是所有字段 包含某些字段 排除某些字段
depth = 1
class BookSerializer(serializers.ModelSerializer):
chapter = serializers.CharField(source="get_chapter_display", read_only=True)
class Meta:
model = Book
fields = "__all__"
# fields = ["id", "title", "pub_time"]
# exclude = ["user"]
# 分別是所有字段 包含某些字段 排除某些字段
depth = 1
read_only_fields = ["id"]
extra_kwargs = {"title": {"validators": [my_validate,]}}
由于depth會讓我們外鍵變成只讀,所以我們再定義一個(gè)序列化的類,其實(shí)只要去掉depth就可以了~~
class BookSerializer(serializers.ModelSerializer):
chapter = serializers.CharField(source="get_chapter_display", read_only=True)
class Meta:
model = Book
fields = "__all__"
# fields = ["id", "title", "pub_time"]
# exclude = ["user"]
# 分別是所有字段 包含某些字段 排除某些字段
read_only_fields = ["id"]
extra_kwargs = {"title": {"validators": [my_validate,]}}
外鍵關(guān)聯(lián)的對象有很多字段我們是用不到的~都傳給前端會有數(shù)據(jù)冗余~就需要我們自己去定制序列化外鍵對象的哪些字段~~
class BookSerializer(serializers.ModelSerializer):
chapter = serializers.CharField(source="get_chapter_display", read_only=True)
user = serializers.SerializerMethodField()
publisher = serializers.SerializerMethodField()
def get_user(self, obj):
# obj是當(dāng)前序列化的book對象
users_query_set = obj.user.all()
return [{"id": user_obj.pk, "name": user_obj.name} for user_obj in users_query_set]
def get_publisher(self, obj):
publisher_obj = obj.publisher
return {"id": publisher_obj.pk, "title": publisher_obj.title}
class Meta:
model = Book
fields = "__all__"
# fields = ["id", "title", "pub_time"]
# exclude = ["user"]
# 分別是所有字段 包含某些字段 排除某些字段
read_only_fields = ["id"]
extra_kwargs = {"title": {"validators": [my_validate,]}
class BookSerializer(serializers.ModelSerializer):
dis_chapter = serializers.SerializerMethodField(read_only=True)
users = serializers.SerializerMethodField(read_only=True)
publishers = serializers.SerializerMethodField(read_only=True)
def get_users(self, obj):
# obj是當(dāng)前序列化的book對象
users_query_set = obj.user.all()
return [{"id": user_obj.pk, "name": user_obj.name} for user_obj in users_query_set]
def get_publishers(self, obj):
publisher_obj = obj.publisher
return {"id": publisher_obj.pk, "title": publisher_obj.title}
def get_dis_chapter(self, obj):
return obj.get_chapter_display()
class Meta:
model = Book
# fields = "__all__"
# 字段是有序的
fields = ["id", "title","dis_chapter", "pub_time", "publishers", "users","chapter", "user", "publisher"]
# exclude = ["user"]
# 分別是所有字段 包含某些字段 排除某些字段
read_only_fields = ["id", "dis_chapter", "users", "publishers"]
extra_kwargs = {"title": {"validators": [my_validate,]}, "user": {"write_only": True}, "publisher": {"write_only": True},
"chapter": {"write_only": True}}
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)cdcxhl.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。