DRF

認(rèn)證實(shí)現(xiàn)

 from rest_framework.authentication import BaseAuthentication
 from rest_framework.exceptions import AuthenticationFailed
 from authapp.models import UserToken

 class MyOrderAuthentication(BaseAuthentication):
        認(rèn)證的邏輯
     def authenticate(self, request):
         token = request._request.GET.get('token')
         # 獲取到token之后,需要在數(shù)據(jù)庫中查找token
         obj = UserToken.objects.filter(token=token).first()
         if not obj:
             # 沒有通過認(rèn)證
             raise AuthenticationFailed('認(rèn)證失敗')
         # 返回元組( user, auth )
         return (obj.user, obj)
 """

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

     # 通過authentication_classes設(shè)置認(rèn)證類
     authentication_classes = [MyOrderAuthentication,]

     # 通過authentication_classes設(shè)置為空列表,就不再進(jìn)行認(rèn)證了
     # authentication_classes = []

 """

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

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

權(quán)限

 from rest_framework.permissions import BasePermission

 class MyOrderPermission(BasePermission):
     #自定義權(quán)限認(rèn)證的類,必須要實(shí)現(xiàn)has_permission方法
     message = '你不是超級用戶,沒有權(quán)限訪問'
     def has_permission(self, request, view):
     
         #Return `True` if permission is granted, `False` otherwise.
         #返回True表示有權(quán)限訪問,返回False表示沒有權(quán)限訪問
         if request.user.user_type != 3:
             return False
         return True  
局部使用

class OrderView(APIView):

     # permission_classes設(shè)置權(quán)限類
     permission_classes = [MyOrderPermission,]
     # 通過authentication_classes設(shè)置為空列表,就不再進(jìn)行權(quán)限認(rèn)證了
     permission_classes = []


全局的設(shè)定

REST_FRAMEWORK = {
   'DEFAULT_PERMISSION_CLASSES':['unitls.permission.MyOrderPermission'],
}

節(jié)流:

VISIT_RECORD = {}
class VisitThrottle(object):

    def __init__(self):
        self.history = None

    def allow_request(self,request,view):
        #實(shí)現(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'],
}

版本

使用 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',
    }
"""



如果使用URLPathVersioning,路由格式如下
"""
    url(r"^(?P<version>[v1|v2]+)/version/",VersionView.as_view(),name='vvvv')
"""

序列化

DRF 序列化
第一種:繼承自serializers.Serializer
"""
     class BookDetailSerializer(serializers.Serializer):
             # 正常的字段序列化
             id = serializers.IntegerField()
             bookname = serializers.CharField()
             author = serializers.CharField()
             category = serializers.IntegerField()
             bookdesc = serializers.CharField()
             

             # 自定義方法獲取字段
             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

解析器

局部使用:
   from rest_framework.parsers import JSONParser,FormParser
在視圖類中:
parser_classes = [FormParser,]
全局使用
REST_FRAMEWORK = {
    'DEFAULT_PARSER_CLASSES':[
        'rest_framework.parsers.JSONParser'
    ]

}

分頁

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()
          #實(shí)例化分頁的類
          #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其實(shí)一樣,只是我們在外面邏輯,
    GenericAPIView在內(nèi)部c定制方法幫我們實(shí)現(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視圖
    如果要實(shí)現(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é)
        只想實(shí)現(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]
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容