【1126 | Day66】drf之频率组件

频率组件

为了防止恶意访问,需要对同一个访问者进行访问频率控制,借此减少服务器压力。

1. 频率组件工作原理

drf频率控制是通过单位时间内访问的次数来实现。

在drf的内部有一个字典,当ip访问的时候,有两种情况:

  • 如果ip1是已经访问的ip,则在记录字典中添加这次的访问时间:{'ip1':[时间1,时间2,最新时间]}

  • 如果IP2是第一次访问,则该字典进行添加操作:{'ip2':[最新访问时间]}

2. 源码阅读

3. 自定义频率控制类

from rest_framework.throttling import BaseThrottle
import time
VISIT_RECORD = {}
class MyThrotting(BaseThrottle):
    def __init__(self):
        self.history=[]
    #方法实现
    def allow_request(self, request, view):
        """
         以IP限流  一分钟同一个IP只能访问五次
        """
        #1:获取发访问一个ip
        ip = request.META.get("REMOTE_ADDR")
        '''
         2:判断当前ip是否存在,如果存在,添加最新的时间,如果不存在添加新的ip
        '''
        now_time=time.time()
        if ip in VISIT_RECORD:
            VISIT_RECORD[ip].insert(0, now_time)
        else:
            VISIT_RECORD[ip]=[now_time]
        history=VISIT_RECORD[ip]
        '''
        3:最后访问的和最新访问的时间相差一秒,删除最早访问的记录。保证字典内的记录均在一分钟以内。
        '''
        while history and history[0] - history[-1] > 60:
            history.pop()
        self.history=history
        """
        4:判断一分钟内,该ip访问次数是不是5次 
        """
        if len(history) > 5:
            return False
        else:
            return True
 
    def wait(self):
        """
        需要等待多长时间,才能再次访问
        """
        time = 60 - (self.history[0] - self.history[-1])
        return time

4. 局部配置和全局配置

5. 框架提供的频率认证组件的使用

a:导入包

from rest_framework.throttling import SimpleRateThrottle

b:settings.py配置

其他一些符号代表的时间频率:
('s', 'sec', 'm', 'min', 'h', 'hour', 'd', 'day')
REST_FRAMEWORK = {
     
    "DEFAULT_THROTTLE_RATES":{
        'WD':'5/m',         #速率配置每分钟不能超过5次访问,WD是scope定义的值,
 
    }
}

c:类的编写

from rest_framework.throttling import BaseThrottle,SimpleRateThrottle
class MyVisitThrottle(SimpleRateThrottle):
    #与settings配置的一样
    scope = "WD"
 
    def get_cache_key(self, request, view):
        return self.get_ident(request)

d:局部使用

class authDemo(APIView):
    throttle_classes=[MyVisitThrottle]
    def get(self, request):
        return Response('测试代码')

猜你喜欢

转载自www.cnblogs.com/fxyadela/p/11938863.html
今日推荐