Django drf:权限、频率控制

本文目录:

一、权限

二、频率控制

 

 

一、权限

  1.权限介绍

    只有超级用户才能访问指定的数据,所以就要用权限组件进行设置

  2.局部使用

    # 单独抽出写一个视图类

from rest_framework.permissions import BasePermission


class MyPer(BasePermission):
    message = '您没有权限'

    def has_permission(self, request, view):
        # 取出当前登录用户
        user = request.user
        # 想取出来用户类型的是中文
        ret = user.get_user_type_display()
        if user.user_type == 0:
            return True
        else:
            return False

    # 嵌套需要权限认证的类上

class Books(APIView):
    # Authlogin类的authenticate验证通过,有返回值,后面在写的类都不校验了
    authentication_classes = [Authlogin]
    permission_classes = [MyPer]

    # 查询方法多个
    def get(self, request, *args, **kwargs):
        response = {'status': 100, 'msg': '登录成功'}
        print(request.user.name)
        print(request.auth)

        book_list = models.Book.objects.all()
        # 第一个参数是要序列化的queryset对象,如果序列化多条,必须指定many=True
        # 问?什么情况下many=False,instance=单个对象的时候
        book_ser = BookSerializer(book_list, many=True)
        print(book_ser.data)
        response['books'] = book_ser.data

        return Response(response)
permission_classes = [MyPer]

  3.全局使用

    #在app中setting文件中配置DEFAULT_PERMISSION_CLASSES":["app01.service.permissions.SVIPPermission",]

REST_FRAMEWORK={
    "DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.Authentication",],
    "DEFAULT_PERMISSION_CLASSES":["app01.service.permissions.SVIPPermission",]
}

 

 

二、频率控制

  1.频率简介  

    为了控制用户对某个url请求的频率,比如,一分钟以内,只能访问三次

  2.自定义频率类,自定义频率规则

    #自定义逻辑

#(1)取出访问者ip
# (2)判断当前ip不在访问字典里,添加进去,并且直接返回True,表示第一次访问,在字典里,继续往下走
# (3)循环判断当前ip的列表,有值,并且当前时间减去列表的最后一个时间大于60s,把这种数据pop掉,这样列表中只有60s以内的访问时间,
# (4)判断,当列表小于3,说明一分钟以内访问不足三次,把当前时间插入到列表第一个位置,返回True,顺利通过
# (5)当大于等于3,说明一分钟内访问超过三次,返回False验证失败

    # 代码实现

class MyThrottles():
    VISIT_RECORD = {}
    def __init__(self):
        self.history=None
    def allow_request(self,request, view):
        #(1)取出访问者ip
        # print(request.META)
        ip=request.META.get('REMOTE_ADDR')
        import time
        ctime=time.time()
        # (2)判断当前ip不在访问字典里,添加进去,并且直接返回True,表示第一次访问
        if ip not in self.VISIT_RECORD:
            self.VISIT_RECORD[ip]=[ctime,]
            return True
        self.history=self.VISIT_RECORD.get(ip)
        # (3)循环判断当前ip的列表,有值,并且当前时间减去列表的最后一个时间大于60s,把这种数据pop掉,这样列表中只有60s以内的访问时间,
        while self.history and ctime-self.history[-1]>60:
            self.history.pop()
        # (4)判断,当列表小于3,说明一分钟以内访问不足三次,把当前时间插入到列表第一个位置,返回True,顺利通过
        # (5)当大于等于3,说明一分钟内访问超过三次,返回False验证失败
        if len(self.history)<3:
            self.history.insert(0,ctime)
            return True
        else:
            return False
    def wait(self):
        import time
        ctime=time.time()
        return 60-(ctime-self.history[-1])

    # 内置频率的局部使用

      写一个类,继承自SimpleRateThrottle,(根据IP限制)问:要根据用户现在怎么写

from rest_framework.throttling import SimpleRateThrottle
class VisitThrottle(SimpleRateThrottle):
    scope = 'luffy'
    def get_cache_key(self, request, view):
        return self.get_ident(request)

      在setting里配置:(一分钟访问三次)

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_RATES':{
        'luffy':'3/m'
    }
}    

      在视图类里使用

throttle_classes = [MyThrottles,]

      错误中文显示

class Course(APIView):
    authentication_classes = [TokenAuth, ]
    permission_classes = [UserPermission, ]
    throttle_classes = [MyThrottles,]

    def get(self, request):
        return HttpResponse('get')

    def post(self, request):
        return HttpResponse('post')
    def throttled(self, request, wait):
        from rest_framework.exceptions import Throttled
        class MyThrottled(Throttled):
            default_detail = '傻逼啊'
            extra_detail_singular = '还有 {wait} second.'
            extra_detail_plural = '出了 {wait} seconds.'
        raise MyThrottled(wait)
View Code

内置频率限制类:

BaseThrottle是所有类的基类:方法:def get_ident(self, request)获取标识,其实就是获取ip,自定义的需要继承它

AnonRateThrottle:未登录用户ip限制,需要配合auth模块用

SimpleRateThrottle:重写此方法,可以实现频率现在,不需要咱们手写上面自定义的逻辑

UserRateThrottle:登录用户频率限制,这个得配合auth模块来用

ScopedRateThrottle:应用在局部视图上的(忽略)

    #全局使用

四 内置频率类及全局使用
REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES':['app01.utils.VisitThrottle',],
    'DEFAULT_THROTTLE_RATES':{
        'luffy':'3/m'
    }
}

 

posted @ 2019-02-23 14:02  仗剑煮大虾  阅读(297)  评论(0编辑  收藏  举报