限制用户一分钟只能访问3次
from rest_framework.throttling import BaseThrottle
import time
'''
11:19:40
VISIT_RECORD={
"127.0.0.1":[11:19:20,11:19:10,11:19:00] # 最近三次的访问时间
}
'''
# 为什么将访问记录放在类外面呢?--> 如果将访问记录放在类中的话,用户每次访问服务器,访问记录就会被重置
Visit_Record = {} # 访问记录
class VisitThrottle(BaseThrottle):
def __init__(self):
self.history_record = None
def allow_request(self, request, view):
'''
限制 IP 每分钟访问不能超过 3 次
:param request:
:return:
'''
# 获取用户当前访问的IP地址
remote_addr = request.META.get("REMOTE_ADDR") # 127.0.0.1
# 获取用户当前访问的时间
current_time = time.time()
# 判断用户是否为第一次访问,若是第一次访问直接放行
if remote_addr not in Visit_Record:
Visit_Record[remote_addr] = [current_time, ]
return True
# 若不是第一次访问,那访问记录中就会有此用户IP地址的历史访问记录
history_record = Visit_Record[remote_addr]
self.history_record = history_record
# 限制用户一分钟访问3次:
# 要点一是限制访问记录中都是一分钟之内的;
while history_record and current_time - history_record[-1] > 60:
history_record.pop()
# 要点二是限制访问记录不能超过3条记录
if len(history_record) < 3:
# 在一分钟之内且访问记录不超过3条,就将当前访问时间添加到访问记录中并放行
history_record.insert(0,current_time)
return True
else:
# 在一分钟之内且访问记录等于或超过3条,就禁止访问
return False
def wait(self):
current_time = time.time() # 用户当前访问时间
# 要考虑在wait方法中怎么引用allow_request方法中的变量?
# 需要先在该类中初始化要引用的变量
return (60-(current_time - self.history_record[-1]))