第一版:
from rest_framework
class VisitThrottle(object): def __init__(self): self.history = None def allow_request(self,request,view): #获取用户IP #remote_addr = request.META.get('REMOTE_ADDR')
remote_addr = self.get_ident(request)
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 - 10: #限制10秒内访问3次 history.pop() if length(history) < 3: history.insert(0,ctime) return True #return False 表示访问频率过高 限制访问 def wait(self): #等待多少秒 才能继续访问 ctime = time.time() return 60 - (ctime - self.history[-1]) class OrderView(APIView): """ 订单业务 """ authentication_classes = [] permission_classes = [] throttle_classes = [VisitThrottle,] def get(self, request, *args, **kwargs): ret = {'code': 1000, 'msg': None, 'data': None} try: ret['data'] = ORDER_DICT except Exception as e: pass return JsonResponse(ret)
全局配置:
"DEFAULT_THROTTLE_CLASSES": ["api.utils.throttle.UserThrottle"], "DEFAULT_THROTTLE_RATES": { "keyword": '3/m', #限制1分钟内访问3次 "keyword2": '10/m', #限制1分钟内访问10次 },
第二版:
from rest_framework.throttle import SimpleRateThrottle class VisitThrottle(SimpleRateThrottle): scope = "keyword" def get_cache_key(self, request, view): return self.get_ident(request) class UserThrottle(SimpleRateThrottle): scope = "keyword2" def get_cache_key(self, request, view): return request.user.username
#scope 传递参数给 settings里面的做限制参数使用
"DEFAULT_THROTTLE_RATES": { "keyword": '3/m', #限制1分钟内访问3次 "keyword2": '10/m', #限制1分钟内访问10次 },
第一版:
- 必须继承 BaseThrottle
- 必须实现 allow_request 和wait 方法
第二版:
- 必须继承 SimpleRateThrottle
- 必须实现 get_cache_key方法 传递参数 scope = “userkey”
- 在settings中 写入限制参数 "userkey": '10/m', #限制1分钟内访问10次