RestFramework之频率组件

一、频率组件的使用

  频率组件的存在对我们这web开发有着很大的影像,它的作用就是限制用户在一段时间内访问的次数。

  下面让我们介绍一下频率组件怎样使用

  1.首先需要导入

from rest_framework.throttling import SimpleRateThrottle

  2.编写我们的频率类

 

class MyThrottle(SimpleRateThrottle):
    scope = "visit_rate"  # 这个值决定了在配置时使用那个变量描述限制的频率

    def get_cache_key(self, request, view):  # 这个方法也是必须要有
        return self.get_ident(request)

  3.最后还需要再setting中配置一下

REST_FRAMEWORK = {
    # 'DEFAULT_THROTTLE_CLASSES': (
    #     'app01.utils.throttle_class.MyThrottle',
    # ),
    'DEFAULT_THROTTLE_CLASSES': (
        'app01.app_thorttle.MyThrottle',
    ),
    "DEFAULT_THROTTLE_RATES": {
        "visit_rate": "5/m",  # 这个参数就是频率类中定义的那个参数scope, 其中第一个数字5表示5次,后面的m表示一分钟,还有s,一秒, h, 一小时, d, 一天
    }
}

duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}

二、作用局部的频率类

  

三、如何自己实现频率组件

  1.编写频率类

import time
from rest_framework.throttling import BaseThrottle


class MyThrottle(BaseThrottle):
    visited_record = {}

    def __init__(self):
        self.history = None

    def allow_request(self, request, my_cbv):

        # 这个my_cbv是源码中传的我们的视图类,这里我们也要传进去
        # print(self.get_ident(request))  # 可以获取本次请求的ip
        ip = request.META.get("REMOTE_ADDR")
        if ip not in self.visited_record:
            self.visited_record[ip] = []

        current_time = time.time()
        history = self.visited_record[ip]
        self.history = history
        print(history)

        while history and current_time - history[-1] > 60:  # 把大于60秒的时间都删掉
            history.pop()

        if len(history) > 2:  # 第三次访问,列表中只有2个值,也满足条件
            return False
        history.insert(0, current_time)
        return True

    def wait(self):
        """
        用于返回还剩多少时间访问;
        
        本次访问时间:9:50:55
        [09:50:30, 09:50:20, 09:50:10]   剩余 60 - (9:50:55 - 09:50:10)秒才能访问
        :return:
        """
        c_time = time.time()
        return 60 - (c_time - self.history[-1])

  2.在视图类中加入

throttle_classes = [MyThrottle]

  效果如图:

  

原文地址:https://www.cnblogs.com/qq631243523/p/10100461.html