限流的使用

  • 配置

    可以在配置文件中,使用DEFAULT_THROTTLE_CLASSESDEFAULT_THROTTLE_RATES进行全局配置

    REST_FRAMEWORK = {
        'DEFAULT_THROTTLE_CLASSES': (
            'rest_framework.throttling.AnonRateThrottle',
            'rest_framework.throttling.UserRateThrottle'
        ),
        'DEFAULT_THROTTLE_RATES': {
            'anon': '100/day',
            'user': '1000/day'
        }
    }
    
  • 可选限流类

    • AnonRateThrottle

      • 限制所有匿名未认证用户,使用IP区分用户
      • 使用DEFAULT_THROTTLE_RATES['anon']来设置频次
    • UserRateThrottle

      • 限制认证用户,使用User id 来区分
      • 使用DEFAULT_THROTTLE_RATES['user']来设置频次
    • ScopedRateThrottle

      • 限制用户对于每个视图的访问频次,使用 ipuser id

      • 配置文件 settings.py

        REST_FRAMEWORK = {
            'DEFAULT_THROTTLE_CLASSES': (
                'rest_framework.throttling.ScopedRateThrottle',
            ),
            'DEFAULT_THROTTLE_RATES': {
                'contacts': '1000/day',
                'uploads': '20/day'
            }
        }
        
      • 限流类

        class ContactListView(APIView):
            throttle_scope = 'contacts'
            # 业务逻辑
            pass
        
        class ContactDetailView(APIView):
            throttle_scope = 'contacts'
            # 业务逻辑
            pass
        
        class UploadView(APIView):
            throttle_scope = 'uploads'
            # 业务逻辑
            pass
        
  • 示例

    from rest_framework.authentication import SessionAuthentication
    from rest_framework.permissions import IsAuthenticated
    from rest_framework.generics import RetrieveAPIView
    from rest_framework.throttling import UserRateThrottle
    
    class BookDetailView(RetrieveAPIView):
        queryset = BookInfo.objects.all()
        serializer_class = BookInfoSerializer
        authentication_classes = [SessionAuthentication]
        permission_classes = [IsAuthenticated]
        throttle_classes = (UserRateThrottle,)
    
        def get(self,request,*args,**kwargs):
          return self.retrieve(request,*args,**kwargs)
    

    DEFAULT_THROTTLE_RATES 可以使用 second, minute, hourday来指明周期。 也可以在具体视图中通过throttle_classess属性来配置,如

    from rest_framework.throttling import UserRateThrottle
    from rest_framework.views import APIView
    
    class ExampleView(APIView):
        throttle_classes = (UserRateThrottle,)
        pass
    

results matching ""

    No results matching ""