内置的频率限制(限制未登录用户)
# 全局使用 限制未登录用户一分钟访问5次
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle',
),
'DEFAULT_THROTTLE_RATES': {
'anon': '5/m',
}
}
##################### views.py
from rest_framework.throttling import BaseThrottle
from rest_framework.permissions import IsAdminUser
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
class TestView4(APIView):
authentication_classes = []
permission_classes = []
def get(self, request, *args, **kwargs):
return Response("我是未登录用户")
# 局部使用
from rest_framework.throttling import BaseThrottle
from rest_framework.permissions import IsAdminUser
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.throttling import AnonRateThrottle
class TestView5(APIView):
authentication_classes = []
permission_classes = []
throttle_classes = [AnonRateThrottle]
def get(self, request, *args, **kwargs):
return Response("我是未登录用户 TestView5")
内置频率限制之限制登录用户的访问频次
# 需求:未登录用户一分钟访问5次 登录用户一分钟访问10次
# setting中
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle'
),
'DEFAULT_THROTTLE_RATES': {
'user': '10/m',
'anon': '5/m',
}
# 局部配置:
在视图类中配一个就行
自定制频率
# 自定制频率类,需要写两个方法
-判断是否限次:没有限次可以请求True,限次了不可以请求False
def allow_request(self, request, view)
-限次后调用,显示还需要等待多长时间才能访问,返回等待的时间seconds数字
def wait(self):
# 自定制的频率限制类
from rest_framework.throttling import BaseThrottle
# 问?需不需要继承BaseThrottle? 可以不继承 鸭子类型
import time
class IPThrottle():
# 定义成类属性
VISIT_DIC = {}
def __init__(self):
self.history_list = []
def allow_request(self, request, view):
"""
#(1)取出访问者ip
#(2)判断当前ip不在访问字典里,添加进去,并且直接返回True,表示第一次访问,在字典里,继续往下走
#(3)循环判断当前ip的列表,有值,并且当前时间减去列表的最后一个时间大于60s,把这种数据pop掉,这样列表中只有60s以内的访问时间,
#(4)判断,当列表小于3,说明一分钟以内访问不足三次,把当前时间插入到列表第一个位置,返回True,顺利通过
#(5)当大于等于3,说明一分钟内访问超过三次,返回False验证失败
:param request:
:param view:
:return:
"""
ip = request.META.get('REMOTE_ADDR')
ctime = time.time()
if ip not in self.VISIT_DIC:
self.VISIT_DIC[ip] = [ctime, ]
return True
self.history_list = self.VISIT_DIC[ip] # 当前访问者时间列表拿出来
while True:
if ctime - self.history_list[-1] > 60:
self.history_list.pop() # 把最后一个移除
else:
break
if len(self.history_list) < 3:
self.history_list.insert(0, ctime)
return True
else:
return False
def wait(self):
# 当前时间,减去列表中最后一个时间
ctime = time.time()
return 60-(ctime-self.history_list[-1])
SimpleRateThrottle源码分析
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
# 当前登录用户的ip地址
self.key = self.get_cache_key(request, view) # key: 'throttle_user_1'
if self.key is None:
return True
# django缓存
# 1)导包:from django.core.cache import cache
# 2)添加缓存:cache.set(key, value, exp)
# 3)获取缓存:cache.get(key, default_value)
# 初次访问缓存为空,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
while self.history and self.history[-1] <= self.now - self.duration:
self.history.pop()
# history的长度与限制次数3进行比较
# history的长度第一次访问0 第二次访问1 第三次访问2 第四次访问3失败
if len(self.history) >= self.num_requests:
# 直接返回False,代表频率限制了
return self.throttle_failure()
# history的长度未达到限制次数3,代表可以访问
# 将当前时间插入到history列表的开头,将history列表作为数据存到缓存中,key是throttle_user_1,过期时间60s
return self.throttle_success()
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)
# 3 m
num, period = rate.split('/') # rate: '3/min'
num_requests = int(num)
duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}[period[0]] # 取字符串第一个字符 m
return (num_requests, duration)
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] # scope: 'user'--->'3/min'
except KeyError:
msg = "No default throttle rate set for '%s' scope" % self.scope
raise ImproperlyConfigured(msg)