DRF鳍怨??舞竿?
即使有很多人都知道京景,我也要說,這是django中的DRF骗奖,全稱django restframe work确徙,
那么你應(yīng)該很快聯(lián)想到它的十大組件!下面將按照十大組件 執(zhí)行的順序 具體介紹
認(rèn)證
看到認(rèn)證這兩個字那肯定登錄是其用處之一执桌,python中使用的話可以自定義認(rèn)證類鄙皇;或者用默認(rèn)的直接在django項目中settings文件中配置RESTFRAME_WORK,這個是在全局生效的仰挣,自定義類寫好之后只要在需要的地方設(shè)置authenication_classess = [自定義認(rèn)證類]伴逸。如果你設(shè)置了全局的認(rèn)證又不想讓某一個視圖進(jìn)行認(rèn)證,只需要把剛剛設(shè)置的改為空列表或是空元祖即可膘壶。
自定義認(rèn)證類
from rest_framework.authentication import BaseAuthentication
from rest_framework.permissions import BasePermission
from rest_framework.exceptions import AuthenticationFailed
from store import models
class Myauthentication(BaseAuthentication):
def authenticate(self,request):
# 實現(xiàn)認(rèn)證邏輯
token = request._request.GET.get('token')
obj = models.Token.objects.filter(token=token).first()
if obj:
return (obj.appid,token)
else:
raise AuthenticationFailed('認(rèn)證失敗')
局部使用
from .authen import Myauthentication
from rest_framework.mixins import CreateModelMixin,
from rest_framework.viewsets import GenericViewSet
class Run(CreateModelMixin,GenericViewSet):
authenication_classes = [Myauthentication] #自定義認(rèn)證類局部使用
全局配置
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
]
}
權(quán)限
和上面一樣错蝴,自定義的寫好之后,局部使用寫permission_classess權(quán)限類颓芭,全局的使用直接在settings文件配置
自定義權(quán)限類
重寫has_object_permission方法
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
# 重寫has_object_permission方法顷锰,自定義權(quán)限類
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
# Instance must have an attribute named `owner`.
#obj相當(dāng)于數(shù)據(jù)庫中的model,這里要把owner改為我們數(shù)據(jù)庫中的user
return obj.user == request.user
局部使用
from .permiss import IsOwnerOrReadOnly
from rest_framework.mixins import CreateModelMixin,
from rest_framework.viewsets import GenericViewSet
class Run(CreateModelMixin,GenericViewSet):
permission_classes= [IsOwnerOrReadOnly] #自定義認(rèn)證類局部使用
全局
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES':['store.utils.permisss.IsOwnerOrReadOnly']
}
節(jié)流
自定義節(jié)流類
VISIT_RECORD = {}
class VisitThrottle(object):
def __init__(self):
self.history = None
def allow_request(self,request,view):
#實現(xiàn)節(jié)流的邏輯
#基于ip做節(jié)流
# #獲取用戶訪問的IP地址
# ip_address = request._request.META.get('REMOTE_ADDR')
ctime = time.time()
# if ip_address not in VISIT_RECORD:
# #第一次訪問的時候?qū)⒃L問的時間存儲在字典中(ip地址為Key,訪問的時間為value值)
# VISIT_RECORD[ip_address] = [ctime,]
#
# #第二次訪問的時候取出訪問的歷史記錄
# history = VISIT_RECORD[ip_address]
# 基于用戶的節(jié)流
username = request.user.username
if username not in VISIT_RECORD:
VISIT_RECORD[username] = [ctime, ]
history = VISIT_RECORD[username]
self.history = history
while history and history[-1] < ctime - 10:
#如果訪問的時間記錄超過60秒,就把超過60秒的時間記錄移除
history.pop()
if len(history) < 6:
history.insert(0,ctime)
return True
return False
def wait(self):
#一旦用戶訪問次數(shù)到達(dá)閥值,顯示用戶需要等待的時間
ctime = time.time()
#09:54:30 09:54:28
return 10 - (ctime - self.history[-1])
局部使用
class OrderView(APIView):
# throttle_classes設(shè)置節(jié)流類
throttle_classes = [VisitThrottle,]
全局設(shè)置
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES':['unitls.throttle.VisitThrottle'],
}
使用DRF內(nèi)置的限頻類
from rest_framework.throttling import SimpleRateThrottle
#推薦使用這種
class VisitThrottle(SimpleRateThrottle):
#沒有登錄用戶亡问,每分鐘訪問10次
scope = 'logined'
def get_cache_key(self, request, view):
return request.user.username
全局設(shè)置
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_RATES':{
'unlogin':'10/m',
'logined':'3/m',
},
'DEFAULT_THROTTLE_CLASSES':['unitls.throttle.VisitThrottle'],
}
版本控制
自定義版本控制類
class ParmasVersion(object):
def determine_version(self, request, *args, **kwargs):
version = request.query_params.get('version')
return version
使用(局部)
class VersionView(APIView):
#設(shè)置獲取版本的類
versioning_class = ParmasVersion
全局設(shè)置
'DEFAULT_VERSIONING_CLASS':'unitls.version.ParmasVersion',
使用 DRF內(nèi)置的版本控制類QueryParameterVersioning(局部)
from rest_framework.versioning import QueryParameterVersioning
class VersionView(APIView):
#設(shè)置獲取版本的類
versioning_class = QueryParameterVersioning
設(shè)置文件中的配置信息
REST_FRAMEWORK = {
'VERSION_PARAM':'version',
'DEFAULT_VERSION':'v1',
'ALLOWED_VERSIONS':['v1','v2'],
}
全局設(shè)置
REST_FRAMEWORK = {
'VERSION_PARAM':'version',
'DEFAULT_VERSION':'v1',
'ALLOWED_VERSIONS':['v1','v2'],
'DEFAULT_VERSIONING_CLASS':'rest_framework.versioning.QueryParameterVersioning',
}
使用 DRF內(nèi)置的版本控制類URLPathVersioning(局部)
from rest_framework.versioning import URLPathVersioning
class VersionView(APIView):
#設(shè)置獲取版本的類
versioning_class = URLPathVersioning
設(shè)置文件中的配置信息
REST_FRAMEWORK = {
'VERSION_PARAM':'version',
'DEFAULT_VERSION':'v1',
'ALLOWED_VERSIONS':['v1','v2'],
}
全局設(shè)置
REST_FRAMEWORK = {
'VERSION_PARAM':'version',
'DEFAULT_VERSION':'v1',
'ALLOWED_VERSIONS':['v1','v2'],
'DEFAULT_VERSIONING_CLASS':'rest_framework.versioning.URLPathVersioning',
}
如果使用URLPathVersioning官紫,路由格式如下
url(r"^(?P<version>[v1|v2]+)/version/",VersionView.as_view(),name='vvvv')
#使用 DRF內(nèi)置的版本控制類URLPathVersioning 反向生成url地址
#反向生成url地址 reverse
obj = request.versioning_scheme
url1 = obj.reverse(viewname='orders',request=request)
#使用django的reverse方法反響生成url地址
from django.urls import reverse
url2 = reverse(viewname='orders',kwargs={'version':'v2'})
解析器
因為開發(fā)人員post請求上傳數(shù)據(jù)時,傳遞的數(shù)據(jù)類型不同,我們可能在request._request.POST中獲取不到數(shù)據(jù)
case1: Content-Type : application/x-www-form-urlencoded
服務(wù)端接收到的post請求的數(shù)據(jù)格式:username=xxxxx&age=18&sex=男
我們就可以在request._request.POST中獲取到數(shù)據(jù)
class UserInfoView(APIView):
def post(self,request,*args,**kwargs):
username = request._request.POST.get('username')
age = request._request.POST.get('age')
sex = request._request.POST.get('sex')
case2:Content-Type:application/json
服務(wù)端接收到的post請求的數(shù)據(jù)格式就是json數(shù)據(jù):{"username":"xxxx","age":"18","sex":"男"}
在request._request.POST中就獲取不到數(shù)據(jù)束世,但是在request.body中可以拿到
class UserInfoView(APIView):
def post(self,request,*args,**kwargs):
import json
data = json.loads(request.body.decode('utf8'))
print(data)
DRF內(nèi)置的解析器FormParser,JSONParser
使用(局部):
from rest_framework.parsers import FormParser,JSONParser
class UserInfoView(APIView):
parser_classes = [FormParser,JSONParser]
#這時DRF 內(nèi)部代碼會根據(jù)request.Content-Type和解析器支持的media_type比較
從而選擇對應(yīng)的解析器
def post(self,request,*args,**kwargs):
# 如果使用JSONParser酝陈、FormParser解析數(shù)據(jù)的話
data = request.data
print(data)
序列化
Django的序列化
#django序例化方式一
books = models.BookInfo.objects.all().values('id','bookname')
books = list(books)
print(type(books), books)
self.ret['books'] = books
#django序例化方式二
books = models.BookInfo.objects.all()
books = [model_to_dict(item) for item in books]
self.ret['books'] = books
DRF 序列化
第一種:繼承自serializers.Serializer
class BookDetailSerializer(serializers.Serializer):
# 正常的字段序列化
id = serializers.IntegerField()
bookname = serializers.CharField()
author = serializers.CharField()
category = serializers.IntegerField()
bookdesc = serializers.CharField()
# 獲取枚舉類型的文本是 source=get_字段名_display
status = serializers.CharField(
source='get_status_display'
)
categoryname = serializers.CharField(
source='get_category_display'
)
# 自定義方法獲取字段
chpaters = serializers.SerializerMethodField()
#序列化時可以自定義方法獲取字段
def get_chpaters(self,row):
""" row - > bookinfo """
chpaters = models.ChpaterInfo.objects.filter(book=row)
ser = ChpaterSerializer(instance=chpaters,many=True,
context=self.context
)
return ser.data
序列化時生成url
url = serializers.HyperlinkedIdentityField(
view_name='chpaterdetail', lookup_field='id',
lookup_url_kwarg='pk',
)
注意:如果序列化類中使用HyperlinkedIdentityField生成url,那我們在序例化時添加context={'request': request}
ser = BookDetailSerializer(
instance=obj,many=False,
context={'request': request}
)
如果出現(xiàn)關(guān)聯(lián)關(guān)系時,獲取model對像的某一個字段
bookname = serializers.CharField(source='book.bookname')
第二種繼承自:serializers.ModelSerializer
class ChpaterDetailSerializer(serializers.ModelSerializer):
#使用ModelSerializer進(jìn)行章節(jié)詳情的序列化
bookname = serializers.CharField(source='book.bookname')
class Meta:
model = models.ChpaterInfo
#fields = "__all__"
fields = ['id','bookname']
DRF (序列化時)自定義方法獲取數(shù)據(jù)
book = serializers.SerializerMethodField()
def get_book(self,row):
""" row - > UserInfo"""
print('======',row.book.all())
ser = UsersBooksSerializer(
instance=row.book.all(),
many=True
)
return ser.data
DRF depth深度的使用
# depth會根據(jù)關(guān)聯(lián)的數(shù)據(jù)不停的深入將數(shù)據(jù)獲取出來(最多不超過10層)
# depth = 1
class UsersSerializer(serializers.ModelSerializer):
class Meta:
model = models.UserInfo
fields = "__all__"
#depth會根據(jù)關(guān)聯(lián)的數(shù)據(jù)不停的深入將數(shù)據(jù)獲取出來(最多不超過10層)
depth = 1
DRF序列化的驗證功能
class UsersSerializer(serializers.ModelSerializer):
#自定義驗證錯誤的信息
username = serializers.CharField(error_messages={'required':'用戶名不能為空'})
class Meta:
model = models.UserInfo
fields = "__all__"
class UsersView(APIView):
def post(self,request,*args,**kwargs):
"""DRF 序列化自帶驗證功能"""
data = request.data
#print(data)
ser = UsersSerializer(data=data)
if ser.is_valid(): # ser.is_valid()y驗證數(shù)據(jù)的有效性
print('驗證后的數(shù)據(jù)',ser.validated_data)
#驗證后的數(shù)據(jù)正確后,保存數(shù)據(jù)至數(shù)據(jù)庫
ser.save()
else:
#上傳數(shù)據(jù)不符合規(guī)范時ser.errors毁涉,返回錯誤詳細(xì)
print(ser.errors)
return Response(data)
自定義字段驗證規(guī)則
class UsersInfoSerializer(serializers.ModelSerializer):
username = serializers.CharField(error_messages={'required':'用戶名不能為空'})
class Meta:
model = models.UserInfo
fields = "__all__"
# 用戶名中必須包含老王兩個字,不包含則認(rèn)為名字無效
def validate_username(self,validated_value):
print(validated_value)
from rest_framework.exceptions import ValidationError
if '老王' not in validated_value:
#驗證不通過沉帮,拋出異常
raise ValidationError('用戶名不合法')
#驗證通過,返回數(shù)據(jù)
return validated_value
分頁
自定義分頁類PageNumberPagination
# 自定制分頁類
class MyPageNumberPagination(PageNumberPagination):
"""http://127.0.0.1:8000/api/userpage/?page=1&pagesize=10"""
# page_size每一返回多少條
page_size = 5
# 設(shè)置分頁的參數(shù)名
page_query_param = 'page'
# 設(shè)置每頁返回數(shù)據(jù)量的參數(shù)名
page_size_query_param = 'pagesize'
# 設(shè)置每頁最大返回的條數(shù)
max_page_size = 6
使用
class UsersPageView(APIView):
def get(self,request,*args,**kwargs):
# 獲取表中所有用戶的row(記錄)
obj = models.UserInfo.objects.all()
#實例化分頁的類
#page_obj = PageNumberPagination()
page_obj = MyPageNumberPagination()
#獲取分頁數(shù)據(jù)
page_data = page_obj.paginate_queryset( queryset=obj,request=request,view=self)
# 序列化
ser = UsersSerializer(instance=page_data,many=True)
# return Response(ser.data)
#get_paginated_response會返回上一頁下一頁和總條數(shù)
return page_obj.get_paginated_response(ser.data)
自定義分頁類LimitOffsetPagination
from rest_framework.pagination import LimitOffsetPagination
class MyLimitOffsetPagination(LimitOffsetPagination):
"""http://127.0.0.1:8000/api/userpage/?limit=10&offset=0"""
default_limit = 5
limit_query_param = 'limit'
offset_query_param = 'offset'
max_limit = 7
自定義分頁類CursorPagination(會對分頁參數(shù)進(jìn)行加密)
from rest_framework.pagination import CursorPagination
class MyCursorPagination(CursorPagination):
"""http://127.0.0.1:8000/api/userpage/?cursor=cD01"""
cursor_query_param = 'cursor'
page_size = 4
#返回數(shù)據(jù)市的排序的方式
ordering = '-id'
max_page_size = 8
設(shè)置全局的分頁
"""
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS':'unitl.pagination.MyCursorPagination',
'PAGE_SIZE':3
}
"""
視圖
以前 (Django的View)
class MyView(View)
.....
現(xiàn)在(rest_framework的APIView)
class MyView(APIView)
.....
其他視圖的使用
第一個:GenericAPIView 視圖的使用 (跟繼承自APIViewq其實一樣薪丁,只是我們在外面邏輯遇西,
GenericAPIView在內(nèi)部c定制方法幫我們實現(xiàn)了)
from rest_framework.generics import GenericAPIView
class BookinfoSeralizer(serializers.ModelSerializer):
class Meta:
model = models.BookInfo
fields = "__all__"
class BookView(GenericAPIView):
# queryset: 設(shè)置獲取的數(shù)據(jù)
queryset = models.BookInfo.objects.all()
# serializer_class: 設(shè)置序列化的類
serializer_class = BookinfoSeralizer
# pagination_class : 設(shè)置分頁的類
pagination_class = MyPageNumberPagination
def get(self,request,*args,**kwargs):
obj = self.get_queryset() #=> obj = models.BookInfo.objects.all()
# 獲取當(dāng)前分頁的數(shù)據(jù)
page_data = self.paginate_queryset(obj) #=>page_obj = MyPageNumberPagination() #獲取分頁數(shù)據(jù)page_data = page_obj.paginate_queryset()
# 獲取序列化之后的數(shù)據(jù)
ser = self.get_serializer(instance=page_data,many=True) #->ser = BookinfoSeralizer(instance=page_data,many=True)
return Response(ser.data)
第二個:GenericViewSet 視圖的如下使用,注意路由會發(fā)生變化
class BookView(GenericViewSet):
# queryset: 設(shè)置獲取的數(shù)據(jù)
queryset = models.BookInfo.objects.all()
# serializer_class: 設(shè)置序列化的類
serializer_class = BookinfoSeralizer
# pagination_class : 設(shè)置分頁的類
pagination_class = MyPageNumberPagination
def list(self,request,*args,**kwargs):
obj = self.get_queryset() #=> obj = models.BookInfo.objects.all()
# 獲取當(dāng)前分頁的數(shù)據(jù)
page_data = self.paginate_queryset(obj) #=>page_obj = MyPageNumberPagination() #獲取分頁數(shù)據(jù)page_data = page_obj.paginate_queryset(
# 獲取序列化之后的數(shù)據(jù)
ser = self.get_serializer(instance=page_data,many=True) #->ser = BookinfoSeralizer(instance=page_data,many=True)
return Response(ser.data)
路由會發(fā)生變化严嗜,配置如下
url(r"bookpage/$",views.BookView.as_view({'get': 'list'}),name='bookpage')
第三個:ListModelMixin,CreateModelMixin,RetrieveModelMixin,
DestroyModelMixin,UpdateModelMixin 等視圖的使用
from rest_framework.mixins import ListModelMixin,CreateModelMixin,RetrieveModelMixin,DestroyModelMixin,UpdateModelMixin
from rest_framework.viewsets import GenericViewSet
# ListModelMixin : 返回列表數(shù)據(jù)據(jù)( get請求)
# CreateModelMixin : 新增一條數(shù)據(jù) (Post請求)
# RetrieveModelMixin, : 獲取詳情數(shù)據(jù) (get請求)
# DestroyModelMixin, : 刪除數(shù)據(jù)的時候 (delete)
# UpdateModelMixin : 跟新數(shù)據(jù)的時候使用 (put)
class BookView(ListModelMixin,RetrieveModelMixin,CreateModelMixin,DestroyModelMixin,UpdateModelMixin,GenericViewSet):
# queryset: 設(shè)置獲取的數(shù)據(jù)
queryset = models.BookInfo.objects.all()
# serializer_class: 設(shè)置序列化的類
serializer_class = BookinfoSeralizer
# pagination_class : 設(shè)置分頁的類
pagination_class = MyPageNumberPagination
第四個:ModelViewSet視圖的使用
ModelViewSet繼承自istModelMixin,CreateModelMixin,
RetrieveModelMixin,DestroyModelMixin,UpdateModelMixin視圖
如果要實現(xiàn)最基本的增刪改查功能粱檀,就直接繼承自ModelViewSet
from rest_framework.viewsets import ModelViewSet
class BookView(ModelViewSet):
# queryset: 設(shè)置獲取的數(shù)據(jù)
queryset = models.BookInfo.objects.all()
# serializer_class: 設(shè)置序列化的類
serializer_class = BookinfoSeralizer
# pagination_class : 設(shè)置分頁的類
pagination_class = MyPageNumberPagination
視圖使用小總結(jié)
只想實現(xiàn)簡單的增刪改查
ModelViewSet
只想增
CreateModelMixin,GenericViewSet
只想增刪改
CreateModelMixin,DestroyModelMixin,UpdateModelMixin,GenericViewSet
如果視圖中的業(yè)務(wù)邏輯復(fù)雜,以上都不能滿足的時候漫玄,直接使用
APIView
#自動路由配置
from django.conf.urls import url,include
from api import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r"bookpage",views.BookView,base_name='bookpage')
urlpatterns = [
url(r'v1/',include(router.urls)),
]
自動路由會生成四個接口
^api/ v1/ ^bookpage/$ [name='bookpage-list']
^api/ v1/ ^bookpage\.(?P<format>[a-z0-9]+)/?$ [name='bookpage-list']
^api/ v1/ ^bookpage/(?P<pk>[^/.]+)/$ [name='bookpage-detail']
^api/ v1/ ^bookpage/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='bookpage-detail']
渲染器
INSTALLED_APPS = [
'rest_framework',
]
from rest_framework.renderers import BrowsableAPIRenderer,JSONRenderer,AdminRenderer
class BookView(ModelViewSet):
# 設(shè)置渲染器類型
renderer_classes = [JSONRenderer]