# SimpleRateThrottle源码分析defget_rate(self):"""
Determine the string representation of the allowed request rate.
"""ifnotgetattr(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]# scope:'user' => '3/min'except KeyError:
msg ="No default throttle rate set for '%s' scope"% self.scope
raise ImproperlyConfigured(msg)defparse_rate(self, rate):"""
Given the request rate string, return a two tuple of:
<allowed number of requests>, <period of time in seconds>
"""if rate isNone:return(None,None)#3 mmmmm
num, period = rate.split('/')# rate:'3/min'
num_requests =int(num)
duration ={'s':1,'m':60,'h':3600,'d':86400}[period[0]]return(num_requests, duration)defallow_request(self, request, view):if self.rate isNone:returnTrue#当前登录用户的ip地址
self.key = self.get_cache_key(request, view)# key:'throttle_user_1'if self.key isNone:returnTrue# 初次访问缓存为空,self.history为[],是存放时间的列表
self.history = self.cache.get(self.key,[])# 获取一下当前时间,存放到 self.now
self.now = self.timer()# Drop any requests from the history which have now passed the# throttle duration# 当前访问与第一次访问时间间隔如果大于60s,第一次记录清除,不再算作一次计数# 10 20 30 40# self.history:[10:23,10:55]# now:10:56while self.history and self.now - self.history[-1]>= self.duration:
self.history.pop()# history的长度与限制次数3进行比较# history 长度第一次访问0,第二次访问1,第三次访问2,第四次访问3失败iflen(self.history)>= self.num_requests:# 直接返回False,代表频率限制了return self.throttle_failure()# history的长度未达到限制次数3,代表可以访问# 将当前时间插入到history列表的开头,将history列表作为数据存到缓存中,key是throttle_user_1,过期时间60sreturn self.throttle_success()