5. DRF 限流

Django DRF 限流

1. 使用

1.1 设置认证全局变量

在settings.py添加如下代码


REST_FRAMEWORK = {
    "DEFAULT_THROTTLE_CLASSES": ['utils.throttle.MineThrottle']
}

1.2 为单个视图方法设置权限

class Home2(APIView):
    throttle_classes = [MineThrottle]
    permission_classes = [MinePermission, MinePermission1, MinePermission2]

    def check_permissions(self, request):
        permission_result = []
        for permission in self.get_permissions():
            permission_result.append(permission.has_permission(request, self))
            if True not in permission_result:
                self.permission_denied(
                    request,
                    message=getattr(permission, 'message', None),
                    code=getattr(permission, 'code', None)
                )

    def get(self, reqeust):
        return JsonResponse({"status": True, 'data': 'OK'})

    def post(self, request):
        print(request.user, request.auth)
        return JsonResponse({"status": True, 'data': 'OK'})

1.3 限制用户一小时只能访问五次

throttling.py中还定义好了名字叫 SimpleRateThrottle的类,我们将要用这个类实现限制用户访问次数

下面看SimpleRateThrottle类中的allow_request方法

分析完成,现在开始写自己的代码

settings.py中设置

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": ['utils.auth.Myauth'],
    "DEFAULT_PERMISSION_CLASSES": ['utils.permission.MinePermission'],
    "DEFAULT_THROTTLE_CLASSES": ['utils.throttle.MineThrottle'],
    "DEFAULT_THROTTLE_RATES": {
        "user": "5/m"
    }
}

throttle.py中设置

from rest_framework.throttling import BaseThrottle, SimpleRateThrottle


class MineThrottle(SimpleRateThrottle):
    scope = "user"

    def get_cache_key(self, request, view):
        if request.user:
            ident = request.user.pk
        else:
            ident = self.get_ident(request)

        return self.cache_format % {
            'scope': self.scope,
            'ident': ident
        }

运行查看结果

连续运行五次后,

限流结束

posted @ 2024-07-12 15:46  khalil12138  阅读(2)  评论(0编辑  收藏  举报