Custom, it is the source of basic logic
'' ' {' IP1 ': [Time 1, Time 2], ' IP2 ': [Time 1,], } # (1) remove the visitor ip # (2) determine the current ip is not accessing the dictionary, added to it, and directly returns True, represents the first visit, in the dictionary, continue to go down # (3) determine the list of currently circulating ip, there is value, and the current time minus the last time the list is more than 60s, put this data pop off, so that only the list of access time less than 60s, # (. 4) is determined, when the list is less than 3, the lack of access times less than a minute, the current time is inserted into the list of the first position, returns True, pass # ( 5) when less than 3, indicating that access to more than three times within a minute, authentication fails and False '' ' class MyThrottle (): visitor_dic = {} DEF the __init__ (Self): self.history = None DEF allow_request (Self, Request, View ): IP = request.META.get ( ' REMOTE_ADDR ') # Out ip address, fixed written # not in the dictionary, that is the first visit ctime = time.time () IF ip not in self.visitor_dic: self.visitor_dic [ip] = [ctime,] return True # according to the current IP visitors, the time taken to access the list History = self.visitor_dic [IP] self.history = History the while History and the ctime - History [-1]> 60: # REVOLVE, a judgment is greater than the last 60, take the second countdown , history.pop () IF len (History) <. 3 : #The current time into the 0th position history.insert (0, the ctime) return True return False DEF the wait (Self): # the remaining time the ctime = the time.time () return 60 - (the ctime - self.history [-1 ])
use
- built-in access frequency control based SimpleRateThrottle - write a class that inherits SimpleRateThrottle - class MyThrottle (SimpleRateThrottle): scope = ' AAA ' # AAA herein must correspond to the setting of the AAA DEF get_cache_key (Self, Request, View): return Self .get_ident (Request) - in the setting: REST_FRAMEWORK = { ' DEFAULT_THROTTLE_RATES ' : { ' AAA ' : ' 10 / m ' # corresponds to the scope of, } } # Later ones analysis: 10 is the number of visits, back side is arbitrary here a # { 'S':. 1, 'm': 60, 'H': 3600, 'D': 86400} ----- ------------------------------- - using # 1, for topical use: written in the view class throttle_classes = [MyThrottle,] # 2, used globally: in the setting: REST_FRAMEWORK = { ' DEFAULT_THROTTLE_CLASSES ' : [ ' app01.MyAuth.MyThrottle ' ,], ' DEFAULT_THROTTLE_RATES ' : { ' AAA ' : ' 10 / m ' } } #3, partially disabled: written in the view class throttle_classes = [] ------------------------------------ --- # error message is displayed :( written into Chinese in the view class) DEF Throttled (Self, request, the wait): class MyThrottled (exceptions.Throttled): default_detail = ' please wait ' extra_detail_singular = ' left {wait } s. ' extra_detail_plural = ' left {wait} seconds ' The raise MyThrottled (the wait)
Source code analysis
Finishing time