For current limiting function
Framework limiting function implemented depends on the encapsulated limiting classes, the arrangement is divided into partial set and global settings, and set a custom class inheriting class settings. If the goal of limiting function you must set DEAFULRT_THROTTLE_CLASSES and DEAFULRT_THROTTLE_RATES
(A), the realization of global settings
. 1 - the settings.py
2 REST_FRAMEWORK = {
. 3
. 4 'DEFAULT_THROTTLE_CLASSES' : [
. 5 'rest_framework.throttling.AnonRateThrottle' , . 6 # restrictor anonymous users . 7 'rest_framework.throttling.UserRateThrottle' . 8 restrictor registered users # 9 } 10 . 11 'DEFAULT_THROTTLE_RATES' : {12 is 'anon': '2 / minute' , 13 is # anonymous users limit per minute visits and 5 14 'user': '5 / minute' , 15 # registered users limit per minute visits 15 to 16 }. 17 - the views.py # 18 is wholly confined class implements a stream function. 19 Demo5APIView (APIView): # 20 is not required to operate in a global setting view class DEF 21 is GET (Self, Request): voting # 22 is page 23 return Response ( 'this is the voting page') 24 --urls.py 25 urlpatterns = [ 26 path('demo7/', views.Demo7APIView.as_view()), 27 ]
(B), to achieve partial set of
. 1. 1 - the settings.py
2 REST_FRAMEWORK = {
. 3 'DEFAULT_THROTTLE_RATES' : {
. 4 'anon': '2 / minute' , 5 # anonymous users to restrict access to five times per minute 6 'user': '5 / minute' , 7 # registered users to restrict access to 15 times per minute 8 } 9 } 10 - implemented views.py 11 # local class current limiting function 12 is Demo6APIView (APIView): = 13 is throttle_classes [UserRateThrottle, AnonRateThrottle] # 14 partial set in view of the need to write a function to set a list of DEF 15 GET (Self, reqeust): 16 return the Response ( 'local test limit function' ). 17 - the urls.py 18 is the urlpatterns = [path. 19 ( 'demo6 / ' , views.Demo6APIView.as_view ()), 20 is]
(C), custom limiting function to achieve
. 1 - the settings.py
2 'DEFAULT_THROTTLE_CLASSES' : [
. 3 'rest_framework.throttling.ScopedRateThrottle' ,
. 4 # limiting custom need to use the class
. 5 ], . 6 . 7 'DEFAULT_THROTTLE_RATES' : { . 8 'Contacts':'. 5 / hour ' , from a defined rate. 9 # restrictor provided 10 }. 11 } 12 is - the views.py flow restrictor 13 is implemented custom # 14 from rest_framework.throttling import function ScopedRateThrottle 15 class Demo7APIView (APIView): 16 throttle_scope =' Contacts '# 17 to set the flow rate limit by Title 18 def throttle_scope GET (self, Request): return the Response. 19 ( "test custom limit function" ) 20 is - URLs.py 21 urlpatterns = [ 22 path('demo7/', views.Demo7APIView.as_view()), 23 ]
(D), the logic of FIG.