DRF的十大组件之认证、权限、节流

1.认证
  定义一个用户表和一个保存用户的Token表

# django的settings文件
REST_FRAMEWORK = {
    # 全局
    "DEFAULT_AUTHENTICATION_CLASSES": ["myutils.auth.MyAuthtication",]
}

在这里插入图片描述
2.权限
  只有VIP用户才能看的内容:
  自定义权限类:

from rest_framework.permissions import BasePermission

class MyPermission(BasePermission):
    message = "sorry,您没有权限"
    def has_permission(self, request, view):
        # 内置封装的方法
        '''
        判断该用户有没有权限
        '''
        # 判断用户是不是VIP用户
        # 如果是VIP用户就返回True
        # 如果是普通用户就返会Flase

        if request.method in ["POST","PUT","DELETE"]:
            # print(111)
            print(request.user.username)
            print(request.user.type)
            print(type(request.user.type))
            if request.user.type == 2:   # 是VIP用户
                print(2222)
                return True
            else:
                return False
        else:
            return True

    def has_object_permission(self, request, view, obj):
        # 用来判断针对的obj权限:
        # 例如:是不是某一个人的评论
        '''
        只有评论人是自己才能删除选定的评论
        '''
        if request.method in ["PUT","DELETE"]:
            print(obj.user.username)
            print(request.user.username)
            if obj.user == request.user:
                # 表示当前评论对象的用户就是登陆用户
                return True
            else:
                return False
        else:
            return True

视图级别配置:

class CommentViewSet(ModelViewSet):
    queryset = models.Comment.objects.all()
    serializer_class = app01_serializers.CommentSerializer
    authentication_classes = [MyAuth,]
    permission_classes = [MyPermission,]

全局级别配置:

复制代码
# REST FRAMEWORK 相关的配置

REST_FRAMEWORK = {
    # 关于认证的全局配置
    # "DEFAULT_AUTHENTICATION_CALSSES": ["app01.utils.auth.MyAuth",],
    # "DEFAULT_PERMISSION_CLASSES" : ["app01.utils.permission.MyPermission"],
    # "DEFAULT_THROTTLE_CLASSES" : ["app01.utils.throttle.MyThrottle",],
    "DEFAULT_THROTTLE_CLASSES" : ["app01.utils.throttle.VisitThrottle",],
    "DEFAULT_THROTTLE_RATES":{
        "XXX":"5/m",
    }
}

3.节流
节流(Throttling)类似于权限,因为它决定了是否应该对请求进行授权。节流表示一个临时状态,并用于控制客户端对API的请求率。

我们可以先编写一个类

class VisitThrottle(object):
    def allow_request(self, request, view):
        return True  # False表示访问频率太高被限制
    def wait(self):
        return None    

在这里插入图片描述

内置控制频率的类

from rest_framework.throttling import BaseThrottle


class VisitThrottle(BaseThrottle):

    def __init__(self):
        self.history = None

    def allow_request(self, request, view):
        # 1. 获取用户ip
        remote_addr = request._request.META.get("REMOTE_ADDR")
        # print(remote_addr)
        # 2. 添加到访问记录中
        ctime = time.time()
        # 当VISIT_RECORD中没有这个记录,可以直接访问,添加一个记录
        if remote_addr not in VISIT_RECORD:
            VISIT_RECORD[remote_addr] = [ctime, ]
            return True
        history = VISIT_RECORD.get(remote_addr)
        self.history = history
        # 拿到最后历史记录里面的最后一个时间,如果最后一个时间小于当前时间-60
        while history and history[-1] < ctime - 60:
            history.pop()
        if len(history) < 3:
            history.insert(0, ctime)
            return True

        return False  # False表示访问频率太高被限制

    def wait(self):
        """
        还需要等多少秒可以访问
        :return:
        """
        ctime = time.time()
        return 60 - (ctime - self.history[-1])
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值