其他分享
首页 > 其他分享> > drf -- 限流组件Throttling

drf -- 限流组件Throttling

作者:互联网

限流组件Throttling

可选限流类

前两类的使用,在配置文件中配置,

x REST_FRAMEWORK = {    'DEFAULT_THROTTLE_CLASSES': ( # 启用的限制类        
                              'rest_framework.throttling.AnonRateThrottle',        
                              'rest_framework.throttling.UserRateThrottle'    ),    
                        'DEFAULT_THROTTLE_RATES': {   # 限制频率        
                                'anon': '100/day',        
                                'user': '1000/day'    
                        }
}

#DEFAULT_THROTTLE_RATES 可以使用 `second`, `minute`, `hour` 或`day`来指明周期,例如:

'DEFAULT_THROTTLE_RATES': {  # 限制频率
        'anon': '3/minute',
        'user': '10/minute',
        'access': '5/minute', # 这个是自定义限流的频率配置
    }

前两类的使用,在视图函数中配置

from rest_framework.throttling import UserRateThrottle
from rest_framework.views import APIView

class ExampleView(APIView):
    throttle_classes = [UserRateThrottle,]
    ...
class ContactListView(APIView):
    throttle_scope = 'contacts'
    ...

class ContactDetailView(APIView):
    throttle_scope = 'contacts'
    ...

class UploadView(APIView):
    throttle_scope = 'uploads'
    ...
REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': (
        'rest_framework.throttling.ScopedRateThrottle',
    ),
    'DEFAULT_THROTTLE_RATES': {
        'contacts': '1000/day',
        'uploads': '20/day'
    }
}

实例代码:

#全局配置中设置访问频率,settings.py代码:
REST_FRAMEWORK = {
    # 权限[全局配置,会被局部配置覆盖]
    # 'DEFAULT_PERMISSION_CLASSES': (
    #     'rest_framework.permissions.IsAuthenticated',
    # ),

    # 限流
    # 'DEFAULT_THROTTLE_CLASSES': (  # 全局启用的限制类
    #     'rest_framework.throttling.AnonRateThrottle', # 匿名用户,游客
    #     'rest_framework.throttling.UserRateThrottle'  # 登录用户
    # ),
    'DEFAULT_THROTTLE_RATES': {  # 限制频率
        'anon': '3/minute',
        'user': '10/minute',
        'access': '5/minute', # 这个是自定义限流的频率配置
    }
}

#视图代码:

from students.models import Student
from students.serializers import StudentModelSerializer
from rest_framework.viewsets import ModelViewSet
from rest_framework.permissions import AllowAny,IsAuthenticated,IsAuthenticatedOrReadOnly,IsAdminUser
from .permission import ISMingGe
from rest_framework.throttling import UserRateThrottle,AnonRateThrottle,ScopedRateThrottle
class Students8APIView(ModelViewSet):
    serializer_class = StudentModelSerializer
    queryset = Student.objects.all()
    # 权限配置
    permission_classes = [AllowAny]
    # 限流配置
    # throttle_classes = [AnonRateThrottle,UserRateThrottle]
    # 自定义限流配置
    throttle_classes = [ScopedRateThrottle]
    throttle_scope = 'access'

标签:THROTTLE,Throttling,--,DEFAULT,framework,限流,rest,throttle
来源: https://www.cnblogs.com/zhiqianggege/p/16221940.html