Throttle (frequency of access) component 1. Detail View Throttle
fromRest_framework.throttlingImportBasethrottlevisit_record={}classVisitthrottle (basethrottle):def __init__(self): Self.history=Nonedefallow_request (Self,request,view): Remote_addr= Request. Meta.get ('REMOTE_ADDR') Print(REMOTE_ADDR)ImportTime CTime=time.time ()ifRemote_addr not inchVisit_record:visit_record[remote_addr]=[CTime,]returnTrue History=visit_record.get (REMOTE_ADDR) self.history= History whileHistory andHistory[-1]<ctime-60: History.pop ()ifLen (History) <3: History.insert (0,ctime)returnTrueElse: returnFalsedefWait (self):ImportTime CTime=time.time ()return60-(Ctime-self.history[-1])
In the views.py:
from Import *class bookviewset (generics. Listcreateapiview): = [Visitthrottle,] = Book.objects.all () = Bookserializers
Global Frequency settings:
rest_framework={ "default_authentication_classes":["app01.service.auth.Authentication",], "default_permission_classes":["app01.service.permissions.SVIPPermission",], "default_throttle_classes": [" App01.service.throttles.VisitThrottle" ,]}Built-in throttle class:
In app01.service.throttles.py modified to:
class Visitthrottle (simpleratethrottle): scope="visit_rate" def Get_cache_key (self, Request, view): return self.get_ident (Request)
Finally, configure in Settings:
rest_framework={ "default_authentication_classes":["app01.service.auth.Authentication",], "default_permission_classes":["app01.service.permissions.SVIPPermission",], "default_throttle_classes":["App01.service.throttles.VisitThrottle",], "default_throttle_rates": { "visit_rate": "5/m" , }}
Rest-framework Frequency Components