天天看點

Django drf:權限、頻率控制

本文目錄:

一、權限

二、頻率控制

  1.權限介紹

    隻有超級使用者才能通路指定的資料,是以就要用權限元件進行設定

  2.局部使用

    # 單獨抽出寫一個視圖類

from rest_framework.permissions import BasePermission


class MyPer(BasePermission):
    message = '您沒有權限'

    def has_permission(self, request, view):
        # 取出目前登入使用者
        user = request.user
        # 想取出來使用者類型的是中文
        ret = user.get_user_type_display()
        if user.user_type == 0:
            return True
        else:
            return False      

    # 嵌套需要權限認證的類上

class Books(APIView):
    # Authlogin類的authenticate驗證通過,有傳回值,後面在寫的類都不校驗了
    authentication_classes = [Authlogin]
    permission_classes = [MyPer]

    # 查詢方法多個
    def get(self, request, *args, **kwargs):
        response = {'status': 100, 'msg': '登入成功'}
        print(request.user.name)
        print(request.auth)

        book_list = models.Book.objects.all()
        # 第一個參數是要序列化的queryset對象,如果序列化多條,必須指定many=True
        # 問?什麼情況下many=False,instance=單個對象的時候
        book_ser = BookSerializer(book_list, many=True)
        print(book_ser.data)
        response['books'] = book_ser.data

        return Response(response)      
permission_classes = [MyPer]      

  3.全局使用

    #在app中setting檔案中配置DEFAULT_PERMISSION_CLASSES":["app01.service.permissions.SVIPPermission",]

REST_FRAMEWORK={
    "DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.Authentication",],
    "DEFAULT_PERMISSION_CLASSES":["app01.service.permissions.SVIPPermission",]
}      

  1.頻率簡介  

    為了控制使用者對某個url請求的頻率,比如,一分鐘以内,隻能通路三次

  2.自定義頻率類,自定義頻率規則

    #自定義邏輯

#(1)取出通路者ip
# (2)判斷目前ip不在通路字典裡,添加進去,并且直接傳回True,表示第一次通路,在字典裡,繼續往下走
# (3)循環判斷目前ip的清單,有值,并且目前時間減去清單的最後一個時間大于60s,把這種資料pop掉,這樣清單中隻有60s以内的通路時間,
# (4)判斷,當清單小于3,說明一分鐘以内通路不足三次,把目前時間插入到清單第一個位置,傳回True,順利通過
# (5)當大于等于3,說明一分鐘内通路超過三次,傳回False驗證失敗      

    # 代碼實作

class MyThrottles():
    VISIT_RECORD = {}
    def __init__(self):
        self.history=None
    def allow_request(self,request, view):
        #(1)取出通路者ip
        # print(request.META)
        ip=request.META.get('REMOTE_ADDR')
        import time
        ctime=time.time()
        # (2)判斷目前ip不在通路字典裡,添加進去,并且直接傳回True,表示第一次通路
        if ip not in self.VISIT_RECORD:
            self.VISIT_RECORD[ip]=[ctime,]
            return True
        self.history=self.VISIT_RECORD.get(ip)
        # (3)循環判斷目前ip的清單,有值,并且目前時間減去清單的最後一個時間大于60s,把這種資料pop掉,這樣清單中隻有60s以内的通路時間,
        while self.history and ctime-self.history[-1]>60:
            self.history.pop()
        # (4)判斷,當清單小于3,說明一分鐘以内通路不足三次,把目前時間插入到清單第一個位置,傳回True,順利通過
        # (5)當大于等于3,說明一分鐘内通路超過三次,傳回False驗證失敗
        if len(self.history)<3:
            self.history.insert(0,ctime)
            return True
        else:
            return False
    def wait(self):
        import time
        ctime=time.time()
        return 60-(ctime-self.history[-1])      

    # 内置頻率的局部使用

      寫一個類,繼承自SimpleRateThrottle,(根據IP限制)問:要根據使用者現在怎麼寫

from rest_framework.throttling import SimpleRateThrottle
class VisitThrottle(SimpleRateThrottle):
    scope = 'luffy'
    def get_cache_key(self, request, view):
        return self.get_ident(request)      

      在setting裡配置:(一分鐘通路三次)

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_RATES':{
        'luffy':'3/m'
    }
}          

      在視圖類裡使用

throttle_classes = [MyThrottles,]      

      錯誤中文顯示

Django drf:權限、頻率控制
Django drf:權限、頻率控制
class Course(APIView):
    authentication_classes = [TokenAuth, ]
    permission_classes = [UserPermission, ]
    throttle_classes = [MyThrottles,]

    def get(self, request):
        return HttpResponse('get')

    def post(self, request):
        return HttpResponse('post')
    def throttled(self, request, wait):
        from rest_framework.exceptions import Throttled
        class MyThrottled(Throttled):
            default_detail = '傻逼啊'
            extra_detail_singular = '還有 {wait} second.'
            extra_detail_plural = '出了 {wait} seconds.'
        raise MyThrottled(wait)      

View Code

内置頻率限制類:

Django drf:權限、頻率控制

BaseThrottle是所有類的基類:方法:def get_ident(self, request)擷取辨別,其實就是擷取ip,自定義的需要繼承它

AnonRateThrottle:未登入使用者ip限制,需要配合auth子產品用

SimpleRateThrottle:重寫此方法,可以實作頻率現在,不需要咱們手寫上面自定義的邏輯

UserRateThrottle:登入使用者頻率限制,這個得配合auth子產品來用

ScopedRateThrottle:應用在局部視圖上的(忽略)

    #全局使用

四 内置頻率類及全局使用
REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES':['app01.utils.VisitThrottle',],
    'DEFAULT_THROTTLE_RATES':{
        'luffy':'3/m'
    }
}