drf节流器源码解析

django框架 2020-07-29 2443

源码:
throttling.py

class BaseThrottle:  
    """  
    Rate throttling of requests.  
    """

    def allow_request(self, request, view):  
        """  
        Return `True` if the request should be allowed, `False` otherwise.  
        """  
        raise NotImplementedError('.allow_request() must be overridden')  

    def get_ident(self, request): # 获取ip  
        """  
        Identify the machine making the request by parsing HTTP_X_FORWARDED_FOR  
        if present and number of proxies is > 0. If not use all of  
        HTTP_X_FORWARDED_FOR if it is available, if not use REMOTE_ADDR.  
        """  
        xff = request.META.get('HTTP_X_FORWARDED_FOR') # 真实ip  
        remote_addr = request.META.get('REMOTE_ADDR')  # 客户端ip  
        num_proxies = api_settings.NUM_PROXIES  

        if num_proxies is not None:  
            if num_proxies == 0 or xff is None:  
                return remote_addr  
            addrs = xff.split(',')  
            client_addr = addrs[-min(num_proxies, len(addrs))]  
            return client_addr.strip()  

        return ''.join(xff.split()) if xff else remote_addr  

    def wait(self):  
        """  
        Optionally, return a recommended number of seconds to wait before  
        the next request.  
        """  
        return None  


class SimpleRateThrottle(BaseThrottle):  
    """  
    A simple cache implementation, that only requires `.get_cache_key()`  
    to be overridden.  

    The rate (requests / seconds) is set by a `rate` attribute on the View  
    class.  The attribute is a string of the form 'number_of_requests/period'.  

    Period should be one of: ('s', 'sec', 'm', 'min', 'h', 'hour', 'd', 'day')  

    Previous request information used for throttling is stored in the cache.  
    """  
    cache = default_cache # 缓存,节流数据保存在内存中  
    timer = time.time  
    cache_format = 'throttle_%(scope)s_%(ident)s'  
    scope = None # 频率值,如'anon'  
    THROTTLE_RATES = api_settings.DEFAULT_THROTTLE_RATES # 频率限制,dict,配置在settings.py  

    def __init__(self):  
        if not getattr(self, 'rate', None):  
            self.rate = self.get_rate() # 限制频率的值,如'500/day'  
        self.num_requests, self.duration = self.parse_rate(self.rate) # parse_rate(),将rate变为元组,解包,500,86400  

    def get_cache_key(self, request, view):  
        """  
        应该返回一个唯一的缓存键,可用于节流。  
        必须重写。  

        如果不应该对请求进行节流,可能会返回“None”。  
        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):  
        """  
        确定允许请求速率的字符串表示形式。  
        Determine the string representation of the allowed request rate.  
        """  
        if not getattr(self, 'scope', None):  
            msg = ("You must set either `.scope` or `.rate` for '%s' throttle" %  
                   self.__class__.__name__)  
            raise ImproperlyConfigured(msg)  

        try:  
            return self.THROTTLE_RATES[self.scope] # 获取配置的值,如'500/day'  
        except KeyError:  
            msg = "No default throttle rate set for '%s' scope" % self.scope  
            raise ImproperlyConfigured(msg)  

    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('/') # 500,  day  
        num_requests = int(num)  
        duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}[period[0]] # 若为d ,则 86400,这个是秒为单位换算  
        return (num_requests, duration) # 总请求数 500, 86400 时间(s)  

    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) # 为字符串,如:throttle_anon_127.0.0.1  
        if self.key is None: # 若值为None,就不拦截  
            return True  
        # self.cache  
        # print(self.cache) # cache.DefaultCacheProxy对象  
        self.history = self.cache.get(self.key, []) # 数组,保存请求时的时间戳,第一次请求为[],第二次如[1596008972.6587608],依此内推  
        self.now = self.timer() # 现在时间的时间戳  

        # Drop any requests from the history which have now passed the  
        # throttle duration  
        # self.now - self.duration 1分钟前  
        # 保存请求时间的数组有值,且最后一次请求的时间小于1分钟前的时间,就抛出  
        # 就是只保存1分钟内的请求次数  
        while self.history and self.history[-1] <= self.now - self.duration:  
            self.history.pop()  
        # 如果1分钟内的请求数量大于设置的最大数量,就表示超限了,不允许访问  
        if len(self.history) >= self.num_requests:  
            return self.throttle_failure()  
        return self.throttle_success()  

    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  

    def throttle_failure(self):  
        """  
        当由于限制而对API的请求失败时调用  
        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.  
        返回建议的下一个请求时间,以秒为单位。  
        """  
        # 访问禁止后,可再次访问的解封时间  
        # 按上面的86400(秒)计算  
        if self.history:  
            # 剩余时间 = 86400 - (现在时间 - 最后一次请求成功的时间)  
            remaining_duration = self.duration - (self.now - self.history[-1])  
        else:  
            remaining_duration = self.duration  
        # 按500计算  
        # 剩余请求数 = 500 - 请求成功的数量 + 1(num_requests,history就可能为0)  
        available_requests = self.num_requests - len(self.history) + 1  
        if available_requests <= 0:  
            return None  

        return remaining_duration / float(available_requests)  

 

标签:django框架

文章评论

评论列表

已有0条评论