频率组件

一:自定义频率类

仿源码自定义频率规则:

class MyThrottles():
    VISIT_RECORD = {}
    def __init__(self):
        self.history=None
    def allow_request(self,request, view):
        #(1)取出访问者ip
        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])
View Code

 

二:内置频率类的使用

定义频率类,必须继承SimpleRateThrottle类:

from rest_framework.throttling import SimpleRateThrottle
class VisitThrottle(SimpleRateThrottle):
# 必须配置scope参数 通过scope参数去settings中找频率限定的规则 scope
= 'throttle'
# 必须定义 get_cache_key函数 返回用户标识的key 这里借用源码中BaseThrottle类(SimpleRateThrottle的父类)中的get_ident函数返回用户ip地址 def get_cache_key(self, request, view): return self.get_ident(request)

局部使用:

视图函数中加上
throttle_classes = [VisitThrottle,]

全局使用:settings中配置

REST_FRAMEWORK={
    'DEFAULT_THROTTLE_CLASSES':['utils.common.VisitThrottle'],
# 局部使用也要在settings中配置上 DEFAULT_THROTTLE_RATES 通过self.scope取频率规则 (一分钟访问3次) 'DEFAULT_THROTTLE_RATES':{'throttle':'3/m',}
}

设置错误信息为中文:

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')
# 函数名为throttled 重写Throttled类中默认的错误信息 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)

 

三:源码分析

源码查看流程:

APIView的dispatch方法()  ---- self.initial(request, *args, **kwargs) ---  self.check_throttles(request)

 

SimpleRateThrottle类详解:

class SimpleRateThrottle(BaseThrottle):
    # 字典 {ip1:[time1,time2],ip2:[time1,time2]} 放在缓存中
    cache = default_cache
    # 获取当前时间
    timer = time.time
    # 做了一个字符串格式化,为登录用户ip限制,配合auth模块使用
    cache_format = 'throttle_%(scope)s_%(ident)s'
    scope = None
    # 从配置文件中取DEFAULT_THROTTLE_RATES
    THROTTLE_RATES = api_settings.DEFAULT_THROTTLE_RATES

    def __init__(self):
        if not getattr(self, 'rate', None):
            # 从配置文件中找出scope配置的名字对应的值
            self.rate = self.get_rate()
        self.num_requests, self.duration = self.parse_rate(self.rate)
    # 这个方法需要重写,否则直接抛异常
    def get_cache_key(self, request, view):
        """
        Should return a unique cache-key which can be used for throttling.
        Must be overridden.

        May return `None` if the request should not be throttled.
        """
        raise NotImplementedError('.get_cache_key() must be overridden')
    
    def get_rate(self):
        if not getattr(self, 'scope', None):
            msg = ("You must set either `.scope` or `.rate` for '%s' throttle" %
                   self.__class__.__name__)
            raise ImproperlyConfigured(msg)

        try:
            # 获取在setting里配置的字典中的值
            return self.THROTTLE_RATES[self.scope]
        except KeyError:
            msg = "No default throttle rate set for '%s' scope" % self.scope
            raise ImproperlyConfigured(msg)
    # 解析 3/m这种传参
    def parse_rate(self, rate):
        """
        Given the request rate string, return a two tuple of:
        <allowed number of requests>, <period of time in seconds>
        """
        if rate is None:
            return (None, None)
        num, period = rate.split('/')
        num_requests = int(num)
        # 只取了第一位,也就是 3/mimmmmmmm也是代表一分钟
        duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}[period[0]]
        return (num_requests, duration)
    # 频率验证逻辑
    def allow_request(self, request, view):
        """
        Implement the check to see if the request should be throttled.

        On success calls `throttle_success`.
        On failure calls `throttle_failure`.
        """
        if self.rate is None:
            return True

        self.key = self.get_cache_key(request, view)
        if self.key is None:
            return True

        self.history = self.cache.get(self.key, [])
        self.now = self.timer()

        # Drop any requests from the history which have now passed the
        # throttle duration
        while self.history and self.history[-1] <= self.now - self.duration:
            self.history.pop()
        if len(self.history) >= self.num_requests:
            return self.throttle_failure()
        return self.throttle_success()
    # 成功返回true,并且插入到缓存中
    def throttle_success(self):
        """
        Inserts the current request's timestamp along with the key
        into the cache.
        """
        self.history.insert(0, self.now)
        self.cache.set(self.key, self.history, self.duration)
        return True
    # 失败返回false
    def throttle_failure(self):
        """
        Called when a request to the API has failed due to throttling.
        """
        return False
    # 计算返回还需等待多长时间
    def wait(self):
        """
        Returns the recommended next request time in seconds.
        """
        if self.history:
            remaining_duration = self.duration - (self.now - self.history[-1])
        else:
            remaining_duration = self.duration

        available_requests = self.num_requests - len(self.history) + 1
        if available_requests <= 0:
            return None

        return remaining_duration / float(available_requests)
View Code

 

posted on 2018-12-14 16:36  叶杨森  阅读(150)  评论(0编辑  收藏  举报