Django-rest-framework 接口实现 限制:(Throttle)

限制:(Throttle)

  • 主要用来限制 单独一个用户的 访问次数

自定义一个 限制类

创建一个Throttle.py(截流)文件

  • 注意 一定要写两个方法

    • def allow_request(self, request, view): allow(允许)

      • 定义限制的逻辑
    • def wait(self): wait (等待)

    • 定义被限制后的等待时间

import time
# 访问记录
visit_record = {}

class MyThrottle(object):
    # 限制访问时间
    VISIT_TIME = 10
    VISIT_COUNT = 3
    # 定义方法 方法名和参数不能变
    def allow_request(self, request, view):
        # 获取登录主机的id 
        id = request.META.get('REMOTE_ADDR')
        self.now = time.time()

        if id not in visit_record:
            visit_record[id] = []

        self.history = visit_record[id]
        # 限制访问时间
        while self.history and self.now - self.history[-1] > self.VISIT_TIME:
            self.history.pop()
        # 此时 history中只保存了最近10秒钟的访问记录
        if len(self.history) >= self.VISIT_COUNT:
            return False
        else:
            self.history.insert(0, self.now)
            return True

    def wait(self):
        return self.history[-1] + self.VISIT_TIME - self.now

使用rest_framework 中已经定义好的 限制 直接配置即可

from rest_framework.throttling import SimpleRateThrottle
# 继承自带的类  定义全局配置 重写  def get_cache_key(self, request, view): 方法
class MyThrottle(SimpleRateThrottle):
    
    scope = "xxx"
    def get_cache_key(self, request, view):
        return self.get_ident(request)
  • rest_framework.throttling 中导入配置

  • 常用 SimpleRateThrottle -- 简单的利率 多少时间内多少次

配置:在settings.py 中配置

全局配置:

REST_FRAMEWORK = {
    # 自定义限制类   也可以直接继承  DRF 中 自带的限制 
    # 'DEFAULT_THROTTLE_CLASSES' = ['auth_demo.throttle.MyThrottle'],
    
    # 使用内置限制类  的额外配置   
    "DEFAULT_THROTTLE_RATES": {
        # key  与定义的 scope 对应 value: 5 表示次数 / m表示分钟  s秒  h小时  d天
        "xxx": "5/m",    
    }
}

局部配置:

扫描二维码关注公众号,回复: 5346617 查看本文章
from auth_demo.throttle import MyThrottle
# 写在要配置的 视图中
throttle_classes = [MyThrottle,]

猜你喜欢

转载自www.cnblogs.com/zhang-zi-yi/p/10447387.html