from rest_framework.throttling Import SimpleRateThrottle Import Time VISIT_RECORD = {} class MyThrottle ( Object ): "" " one minute to allow access to five times " "" DEF the __init __ (Self): self.history = [] DEF allow_request (Self, Request, View ): # get the user's IP address ip = request.META. gET ( " REMOTE_ADDR " , "" ) # self.key = self.get_cache_key () # self.cache. gET (self.key, []) IF ip not in VISIT_RECORD: VISIT_RECORD [ip] = [time.time (),] the else : History = VISIT_RECORD [ip] self.history = History history.insert ( 0 , time.time ()) # ensure that the list is to allow time within the scope of the while self.history [ 0 ] - self.history [- . 1 ]> 60 : self.history.pop () # list length is determined IF Not len (self.history) <= . 5 : return False return True # wait # [recent time, the oldest time] DEF the wait (Self): return 60 - (self.history [ 0 ] - self.history [- 1 ])
class DRFThrottle(SimpleRateThrottle): scope = "WD" def get_cache_key(self, request, view): # 拿IP地址 return self.get_ident(request)