Django rest framework框架中有哪些組件

  • 認證 
  • 權限(受權)
  • 用戶訪問次數/頻率限制 
  • 版本 
  • 解析器(parser)
  • 序列化 
  • 分頁 
  • 路由系統 
  • 視圖 
  • 渲染器 

認證

自定義認證的類
 """
 from rest_framework.authentication import BaseAuthentication
 from rest_framework.exceptions import AuthenticationFailed
 from appname.models import UserToken

 class MyOrderAuthentication(BaseAuthentication):
        在這裏實現認證的邏輯
     def authenticate(self, request):
         token = request._request.GET.get('token')
         # 獲取到token以後,須要在數據庫中查找token
         obj = UserToken.objects.filter(token=token).first()
         if not obj:
             # 沒有經過認證
             raise AuthenticationFailed('認證失敗')
         # 返回元組( user, auth )
         return (obj.user, obj)
 """

使用局部配置(在視圖函數中)
 """
 class OrderView(APIView):

     # 經過authentication_classes設置認證類
     authentication_classes = [MyOrderAuthentication,]

     # 經過authentication_classes設置爲空列表,就再也不進行認證了
     # authentication_classes = []

 """

全局配置
 """
 REST_FRAMEWORK = {
     'DEFAULT_AUTHENTICATION_CLASSES':['unitls.authentication.MyOrderAuthentication'],
 }
 """

設置匿名用戶
 """
 REST_FRAMEWORK = {
     'UNAUTHENTICATED_USER': lambda :"匿名用戶",
     'UNAUTHENTICATED_TOKEN': lambda :'123456',
 }
 """

權限

 自定義權限類
 """
 from rest_framework.permissions import BasePermission

 class MyOrderPermission(BasePermission):
     #自定義權限認證的類,必需要實現has_permission方法
     message = '你不是超級用戶,沒有權限訪問'
     def has_permission(self, request, view):

         #Return `True` if permission is granted, `False` otherwise.
         #返回True表示有權限訪問,返回False表示沒有權限訪問
         if request.user.user_type != 3:
             return False
         return True
 """

 局部使用
 """
  class OrderView(APIView):

     # permission_classes設置權限類
     permission_classes = [MyOrderPermission,]
     # 經過authentication_classes設置爲空列表,就再也不進行權限認證了
     permission_classes = []
 """

 全局的設定
 """
REST_FRAMEWORK = {
   'DEFAULT_PERMISSION_CLASSES':['unitls.permission.MyOrderPermission'],
}
 """

節流

 自定義節流類
 """
VISIT_RECORD = {}
class VisitThrottle(object):

    def __init__(self):
        self.history = None

    def allow_request(self,request,view):
        #實現節流的邏輯
        #基於ip作節流
        # #獲取用戶訪問的IP地址
        # ip_address = request._request.META.get('REMOTE_ADDR')
        ctime = time.time()
        # if ip_address not in VISIT_RECORD:
        #     #第一次訪問的時候將訪問的時間存儲在字典中(ip地址爲Key,訪問的時間爲value值)
        #     VISIT_RECORD[ip_address] = [ctime,]
        #
        # #第二次訪問的時候取出訪問的歷史記錄
        # history = VISIT_RECORD[ip_address]

        # 基於用戶的節流
        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):
        #一旦用戶訪問次數到達閥值,顯示用戶須要等待的時間
        ctime = time.time()
                    #09:54:30    09:54:28
        return 10 - (ctime - self.history[-1])
 """

 局部使用
 """
   class OrderView(APIView):
       # throttle_classes設置節流類
       throttle_classes = [VisitThrottle,]
 """

 全局設置
 """
REST_FRAMEWORK = {
   'DEFAULT_THROTTLE_CLASSES':['unitls.throttle.VisitThrottle'],
}
 """

 使用DRF內置的限頻類
"""
from rest_framework.throttling import SimpleRateThrottle

#推薦使用這種
class VisitThrottle(SimpleRateThrottle):
    #沒有登陸用戶,每分鐘訪問10次
    scope = 'logined'
    def get_cache_key(self, request, view):
    return request.user.username
"""

 全局設置
"""
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):
        #設置獲取版本的類
        versioning_class = ParmasVersion
"""

全局設置
"""
     'DEFAULT_VERSIONING_CLASS':'unitls.version.ParmasVersion',
"""

使用 DRF內置的版本控制類QueryParameterVersioning(局部)
"""
    from rest_framework.versioning import QueryParameterVersioning
    class VersionView(APIView):
        #設置獲取版本的類
        versioning_class = QueryParameterVersioning
"""

設置文件中的配置信息
"""
    REST_FRAMEWORK = {
        'VERSION_PARAM':'version',
        'DEFAULT_VERSION':'v1',
        'ALLOWED_VERSIONS':['v1','v2'],
    }
"""

全局設置
"""
    REST_FRAMEWORK = {
        'VERSION_PARAM':'version',
        'DEFAULT_VERSION':'v1',
        'ALLOWED_VERSIONS':['v1','v2'],
        'DEFAULT_VERSIONING_CLASS':'rest_framework.versioning.QueryParameterVersioning',
    }
"""

使用 DRF內置的版本控制類URLPathVersioning(局部)
"""
    from rest_framework.versioning import URLPathVersioning
    class VersionView(APIView):
        #設置獲取版本的類
        versioning_class = URLPathVersioning
    """

設置文件中的配置信息
"""
    REST_FRAMEWORK = {
        'VERSION_PARAM':'version',
        'DEFAULT_VERSION':'v1',
        'ALLOWED_VERSIONS':['v1','v2'],
    }
    """

全局設置
"""
    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內置的版本控制類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'})
"""

解析器

由於開發人員post請求上傳數據時,傳遞的數據的類型不一樣,咱們可能在request._request.POST中獲取不到數據。數據庫

case1: Content-Type : application/x-www-form-urlencoded
服務端接收到的post請求的數據格式:username=xxxxx&age=18&sex=男
咱們就能夠在request._request.POST中獲取到數據
"""
    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
服務端接收到的post請求的數據格式就是json數據:{"username":"xxxx","age":"18","sex":""}
在request._request.POST中就獲取不到數據,可是在request.body中能夠拿到
"""
    class UserInfoView(APIView):
        def post(self,request,*args,**kwargs):
            import json
            data = json.loads(request.body.decode('utf8'))
            print(data)
"""

DRF內置的解析器FormParser,JSONParser
使用(局部):
"""
   from rest_framework.parsers import FormParser,JSONParser
   class UserInfoView(APIView):
        parser_classes = [FormParser,JSONParser]

        #這時DRF 內部代碼會根據request.Content-Type和解析器支持的media_type比較
        從而選擇對應的解析器

        def post(self,request,*args,**kwargs):
            # 若是使用JSONParser、FormParser解析數據的話
            data = request.data
            print(data)

"""

使用(全局配置解析器):

序列化

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}
    )
"""

若是出現關聯關係時,獲取model對像的某一個字段
"""
    bookname = serializers.CharField(source='book.bookname')
"""

第二種繼承自:serializers.ModelSerializer
"""
class ChpaterDetailSerializer(serializers.ModelSerializer):
    #使用ModelSerializer進行章節詳情的序列化
    bookname = serializers.CharField(source='book.bookname')
    class Meta:
        model = models.ChpaterInfo
        #fields = "__all__"
        fields = ['id','bookname']
"""

DRF (序列化時)自定義方法獲取數據
"""
    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會根據關聯的數據不停的深刻將數據獲取出來(最多不超過10層)
# depth = 1
"""
class UsersSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserInfo
        fields = "__all__"
        #depth會根據關聯的數據不停的深刻將數據獲取出來(最多不超過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驗證數據的有效性
            print('驗證後的數據',ser.validated_data)
            #驗證後的數據正確後,保存數據至數據庫
            ser.save()
        else:
            #上傳數據不符合規範時ser.errors,返回錯誤詳細
            print(ser.errors)
        return Response(data)
"""

自定義字段驗證規則
"""
    class UsersInfoSerializer(serializers.ModelSerializer):
    username = serializers.CharField(error_messages={'required':'用戶名不能爲空'})
        class Meta:
            model = models.UserInfo
            fields = "__all__"

        # 用戶名中必須包含老王兩個字,不包含則認爲名字無效
        def validate_username(self,validated_value):
            print(validated_value)
            from rest_framework.exceptions import ValidationError
            if '老王' not in validated_value:
            #驗證不經過,拋出異常
                raise ValidationError('用戶名不合法')
            #驗證經過,返回數據
            return validated_value
"""

分頁

自定義分頁類PageNumberPagination
  # 自定製分頁類
class MyPageNumberPagination(PageNumberPagination):
    """http://127.0.0.1:8000/api/userpage/?page=1&pagesize=10"""
    # page_size每一返回多少條
    page_size = 5
    # 設置分頁的參數名
    page_query_param = 'page'
    # 設置每頁返回數據量的參數名
    page_size_query_param = 'pagesize'
    # 設置每頁最大返回的條數
    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()
          #獲取分頁數據
          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會返回上一頁下一頁和總條數
          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(會對分頁參數進行加密)
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
    #返回數據市的排序的方式
    ordering = '-id'
    max_page_size = 8

 設置全局的分頁
 """
     REST_FRAMEWORK = {
         'DEFAULT_PAGINATION_CLASS':'unitl.pagination.MyCursorPagination',
         'PAGE_SIZE':3
     }
 """

視圖

之前 (Django的View)
"""
    class MyView(View)
        .....
"""

如今(rest_framework的APIView)
"""
    class MyView(APIView)
    .....
"""

其餘視圖的使用
第一個:GenericAPIView 視圖的使用 (跟繼承自APIViewq其實同樣,只是咱們在外面邏輯,
    GenericAPIView在內部c定製方法幫咱們實現了)
"""
from rest_framework.generics import GenericAPIView

class BookinfoSeralizer(serializers.ModelSerializer):

    class Meta:
        model = models.BookInfo
        fields = "__all__"

class BookView(GenericAPIView):
    # queryset: 設置獲取的數據
    queryset = models.BookInfo.objects.all()
    # serializer_class: 設置序列化的類
    serializer_class = BookinfoSeralizer
    # pagination_class : 設置分頁的類
    pagination_class = MyPageNumberPagination
    def get(self,request,*args,**kwargs):
        obj = self.get_queryset() #=> obj = models.BookInfo.objects.all()
        # 獲取當前分頁的數據
        page_data = self.paginate_queryset(obj) #=>page_obj = MyPageNumberPagination() #獲取分頁數據page_data = page_obj.paginate_queryset()
        # 獲取序列化以後的數據
        ser = self.get_serializer(instance=page_data,many=True) #->ser = BookinfoSeralizer(instance=page_data,many=True)
        return Response(ser.data)
"""

 第二個:GenericViewSet 視圖的以下使用,注意路由會發生變化
    """
    class BookView(GenericViewSet):
        # queryset: 設置獲取的數據
        queryset = models.BookInfo.objects.all()
        # serializer_class: 設置序列化的類
        serializer_class = BookinfoSeralizer
        # pagination_class : 設置分頁的類
        pagination_class = MyPageNumberPagination

        def list(self,request,*args,**kwargs):

            obj = self.get_queryset() #=> obj = models.BookInfo.objects.all()
            # 獲取當前分頁的數據
            page_data = self.paginate_queryset(obj) #=>page_obj = MyPageNumberPagination() #獲取分頁數據page_data = page_obj.paginate_queryset(
            # 獲取序列化以後的數據
            ser = self.get_serializer(instance=page_data,many=True) #->ser = BookinfoSeralizer(instance=page_data,many=True)

            return Response(ser.data)
    """
    路由會發生變化,配置以下
    """
    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 : 返回列表數據據( get請求)
    # CreateModelMixin  : 新增一條數據 (Post請求)
    # RetrieveModelMixin,  : 獲取詳情數據 (get請求)
    # DestroyModelMixin,   : 刪除數據的時候 (delete)
    # UpdateModelMixin  : 跟新數據的時候使用 (put)

    class BookView(ListModelMixin,RetrieveModelMixin,CreateModelMixin,DestroyModelMixin,UpdateModelMixin,GenericViewSet):
        # queryset: 設置獲取的數據
        queryset = models.BookInfo.objects.all()
        # serializer_class: 設置序列化的類
        serializer_class = BookinfoSeralizer
        # pagination_class : 設置分頁的類
        pagination_class = MyPageNumberPagination
    """

    第四個:ModelViewSet視圖的使用
    ModelViewSet繼承自istModelMixin,CreateModelMixin,
    RetrieveModelMixin,DestroyModelMixin,UpdateModelMixin視圖
    若是要實現最基本的增刪改查功能,就直接繼承自ModelViewSet
    """
    from rest_framework.viewsets import ModelViewSet
    class BookView(ModelViewSet):
        # queryset: 設置獲取的數據
        queryset = models.BookInfo.objects.all()
        # serializer_class: 設置序列化的類
        serializer_class = BookinfoSeralizer
        # pagination_class : 設置分頁的類
        pagination_class = MyPageNumberPagination
    """

    視圖使用小總結
        只想實現簡單的增刪改查
            ModelViewSet
        只想增
            CreateModelMixin,GenericViewSet
        只想增刪改
            CreateModelMixin,DestroyModelMixin,UpdateModelMixin,GenericViewSet

        若是視圖中的業務邏輯複雜,以上都不能知足的時候,直接使用
            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):
    # 設置渲染器類型
    renderer_classes = [JSONRenderer]
相關文章
相關標籤/搜索