访问记录 = { 身份证号: [ 12:10:07 ,12:10:06, 12:10:05] } #12:10:10 ,12:10:8,12:10:10 ,12:10:8, #12:10:08 #[12:10:07, 12:10:06, 12:10:05] #访问记录 = { 用户IP: [...] } import time VISIT_RECORD = {} #存放IP的数据库 可以放在缓存! from rest_framework.thrittling import BaseThrottle class VisitThrattle(object): def __init__(self): self.history = None def allow_request(self, request, view): """ 写一些业务逻辑 获取用户IP地址 60s内只能访问3次 """ remote_addr = request._request.META.get('REMOTE_ADDR') print(remote_addr) #访问记录IP ctime = time.time() if remote_addr not in VISIT_RECORD: VISIT_RECORD[remote_addr] = [ctime,] #表示第一次访问 return True history = VISIT_RECORD.get(remote_addr) self.history = history while history and history[[-1] < ctime -60: history.pop() if len(history) < 3: history.insert(0, ctime) return True return False return True #判断是否可以继续访问 True可以访问 频率没有达到最大 #return False如果返回False频率太高,已经被限制 无法继续下一步访问 def wait(self): #显示还需要等多少秒 ctime = time.time() return = 60 - (ctime - self.history[-1]) class AuthView(APIView): authentication_calsses = [] permission_classes = [] throttle_classes = [VisitThrattle,] def post(self, request, *args, **kwargs): #去 request获取IP #访问记录 全局配置的话 REST_FRAMEWORK = { "DEFAULT_THROTTLE_CLASSES" : ['api.utlis.throttle.VisitThrottle'] } 内置控制频率的类: BaseThrottle SimpleRateThrottle(BaseThrottle) allow_request from rest_framework.throttling import BaseThrottle, SimpleRateThrottle class VisitThrottle(SimpleRateThrottle): #对匿名用户的ip号通过时间做访问频率控制 scope = 'Luffy' #指定setting配置文件中Luffy(key) def get_cache_key(self, request, view): #去缓存里取数据 return self.get_ident(request) class UserThrottle(SimpleRateThrottle): #对用户的名字 通过时间做访问频率控制 scope = "LuffyUser" def get_cache_key(self, request, view): return request.user.username 然后再views.py添加 from api.utils.throttle import UserThrottle 在创建的函数里添加 throttle_classes = ["UserThrottle"] 在setting.py加 REST_FRAMEWORK = { "DEFAULT_THROTTLE_CLASSES":['api.utils.throttle.VisitThrottle'], "DEFAULT_THROTTLE_RATES":{ "Luffy":'3/m' #每分钟访问3次 #duration = {'s':1, 'm':60, 'h':3600, 'd':86400}[period[0]] "LuffyUser": 10/m } } 梳理: a. 基本使用 -类, 继承BaseThrottle 实现 allow_request wait 两个方法 加个__init__构造函数 -类, 继承SimpleRateThrottle 实现 get_cache_key scope = "Luffy" (配置文件中的key) b. 局部使用 class AuthView(APIView): throttle_classes = [ VisitThrottle, ] #>>>>>> 全局 REST_FRAMEWORK = { "DEFAULT_THROTTLE_CLASSES":['api.utils.throttle.VisitThrottle'], "DEFAULT_THROTTLE_RATES":{ "Luffy":'3/m' #每分钟访问3次 #duration = {'s':1, 'm':60, 'h':3600, 'd':86400}[period[0]] "LuffyUser": 10/m } }