REST-framework快速构建API--频率

前面已经了解了API的认证和授权。认证,是对资源访问者的第一道门,必须有钥匙,你才能进来拿我的资源;授权,是对资源访问者的第二道门,虽然你进来了,但是你可以拿走什么资源,还是我说了算,就是授权。

当然,为了考虑到服务器的压力情况,资源也不是无限制可以被拿走的,必须要对拿资源的频率做一定的控制,REST-framework在频率限制上也已考虑到了,就是Throttle。

一、自定义频率控制

1、自定义频率控制函数

在utils.py中定义频率控制函数,

from rest_framework.throttling import BaseThrottle
import time
VISIT_RECORD = {}   #保存访问记录

class VisitThrottle(BaseThrottle):
    '''多长时间内内能访问多少次'''
    def __init__(self):
        self.history = None   

    def allow_request(self,request,view):
        #获取用户ip (get_ident)
        remote_addr = self.get_ident(request)
        ctime = time.time()
        #如果当前IP不在访问记录里面,就添加到记录
        if remote_addr not in VISIT_RECORD:
            VISIT_RECORD[remote_addr] = [ctime,]    
            return True    #True表示可以访问
        #获取当前ip的历史访问记录
        history = VISIT_RECORD.get(remote_addr)
        #历史记录保存
        self.history = history

        #如果有历史访问记录,并且最早一次的访问记录离当前时间超过60s,就删除最早的那个访问记录,
        #只要为True,就一直循环删除最早的一次访问记录
        while history and history[-1] < ctime - 60:
            history.pop()
        #并且如果访问记录不超过三次,就把当前的访问记录插到第一个位置(pop删除最后一个)
        if len(history) < 3:
            history.insert(0,ctime)
            return True

    def wait(self):
        '''还需要等多久才能访问'''
        ctime = time.time()
        return 60 - (ctime - self.history[-1])

  

注意:allow_request和wait函数,是重载。

2、应用

局部应用

from app01.service.throttles import *

class BookViewSet(generics.ListCreateAPIView):
    throttle_classes = [VisitThrottle,]
    queryset = Book.objects.all()
    serializer_class = BookSerializers

  

全局应用

REST_FRAMEWORK={
    "DEFAULT_AUTHENTICATION_CLASSES":["app01.utils.TokenAuth",],
    "DEFAULT_THROTTLE_CLASSES":["app01.utils.VisitThrottle",],
}

  

二、自带频率控制

1、定义频率限制函数

utils.py

class VisitThrottle(SimpleRateThrottle):

    scope="visit_rate"
    def get_cache_key(self, request, view):

        return self.get_ident(request)

  

2、应用

局部应用

from app01.service.throttles import *

class BookViewSet(generics.ListCreateAPIView):
    throttle_classes = [VisitThrottle,]
    queryset = Book.objects.all()
    serializer_class = BookSerializers

  

全局应用

REST_FRAMEWORK={
    "DEFAULT_AUTHENTICATION_CLASSES":["app01.utils.TokenAuth",],
    "DEFAULT_THROTTLE_CLASSES":["app01.utils.VisitThrottle",],
     #自带频率控制
        "DEFAULT_THROTTLE_RATES":{
            "visit_rate":"5/m",
        }
}

  

三、效果图

1、正常访问

2、受限访问

猜你喜欢

转载自www.cnblogs.com/skyflask/p/10404425.html
今日推荐