drf限流

drf框架的限流(Throtting)分为全局限流和局部限流两种。提供了基本的根据用户访问次数限流的方法。

全局限流

# settings中添加代码
REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle'
    ],
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/day',
        'user': '1000/day'
    }
}

局部限流

局部限流是针对某个视图进行的限制,仍然需要在settings中做上述配置。局部限流优先于全局限流。

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

# CBV模式下
class ExampleView(APIView):
    throttle_classes = [UserRateThrottle]

    def get(self, request, format=None):
        content = {
            'status': 'request was permitted'
        }
        return Response(content)

# FBV模式下
@api_view(['GET'])
@throttle_classes([UserRateThrottle])
def example_view(request, format=None):
    content = {
        'status': 'request was permitted'
    }
    return Response(content)

可选限流 ScopedRateThrottle

drf还提供了可选限流。可选限流可以自定义限流名称等,全局定义,局部使用。

# settings中添加代码
REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.ScopedRateThrottle',
    ],
    'DEFAULT_THROTTLE_RATES': {
        'contacts': '1000/day',
        'uploads': '20/day'
    }
}

视图中添加settings配置文件中所配置的限制。

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

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

class UploadView(APIView):
    throttle_scope = 'uploads'
    ...
posted @ 2021-02-20 14:20  dsprain  阅读(299)  评论(0)    收藏  举报