限流功能的实现
框架中限流功能的实现依赖于封装好的限流类,设置方式上分为全局设置和局部设置、继承类设置和自定义类设置。如果要实现限流功能则必须设置DEAFULRT_THROTTLE_CLASSES和DEAFULRT_THROTTLE_RATES
(一)、全局设置的实现
1 --settings.py
2 REST_FRAMEWORK = {
3
4 'DEFAULT_THROTTLE_CLASSES': [
5 'rest_framework.throttling.AnonRateThrottle',
6 # 匿名用户的限流
7 'rest_framework.throttling.UserRateThrottle'
8 # 注册用户的限流
9 }
10
11 'DEFAULT_THROTTLE_RATES': { 12 'anon': '2/minute', 13 # 匿名用户每分钟限制访问次数为5次 14 'user': '5/minute', 15 # 注册用户每分钟限制访问次数为15次 16 } 17 --views.py 18 # 全局限流功能的实现 19 class Demo5APIView(APIView): 20 # 全局设置不需要在视图类中进行操作 21 def get(self, request): 22 # 投票页面 23 return Response('这是投票页面') 24 --urls.py 25 urlpatterns = [ 26 path('demo7/', views.Demo7APIView.as_view()), 27 ]
(二)、局部设置的实现
1 1 --settings.py
2 REST_FRAMEWORK = {
3 'DEFAULT_THROTTLE_RATES': {
4 'anon': '2/minute',
5 # 匿名用户每分钟限制访问次数为5次
6 'user': '5/minute',
7 # 注册用户每分钟限制访问次数为15次
8 } 9 } 10 --views.py 11 # 局部限流功能的实现 12 class Demo6APIView(APIView): 13 throttle_classes = [UserRateThrottle, AnonRateThrottle] 14 # 局部设置需要写在视图函数中,以列表的形式来设置 15 def get(self, reqeust): 16 return Response('测试局部限流功能') 17 --urls.py 18 urlpatterns =[ 19 path('demo6/', views.Demo6APIView.as_view()), 20 ]
(三)、自定义限流功能的实现
1 --settings.py
2 'DEFAULT_THROTTLE_CLASSES': [
3 'rest_framework.throttling.ScopedRateThrottle',
4 # 自定义限流需要用到的类
5 ],
6
7 'DEFAULT_THROTTLE_RATES': {
8 'contacts': '5/hour', 9 # 自定义限流的速率设置 10 } 11 } 12 --views.py 13 # 自定义限流功能的实现 14 from rest_framework.throttling import ScopedRateThrottle 15 class Demo7APIView(APIView): 16 throttle_scope = 'contacts' 17 # 通过throttle_scope来设置限流速率名称 18 def get(self, request): 19 return Response("测试自定义限流功能") 20 -- urls.py 21 urlpatterns = [ 22 path('demo7/', views.Demo7APIView.as_view()), 23 ]
(四)、逻辑图