framework —— throttles(访问频率控制)

framework —— throttles(访问频率控制)

1.目录结构

  

2.views.py

from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
# Create your views here.

RECORD = {
    # "1.1.1.1":[150131516161,]
}

class MyThrottle(object):
    def allow_request(self, request, view):
        """
        Return `True` if the request should be allowed, `False` otherwise.
        a.对匿名用户进行限制:每个用户1分钟允许访问10次
            1.获取用户ip,在request里面。
            2.拿到之后,对它进行限制
            3.怎么限制? 用一个字典来约束限制
            4.如果ip不在字典,就表示新增加的,就加到字典里,以ip为key,时间戳为value。
            5.约束条件:一分钟以内的保留,一分钟以外的剔除
            6.添加时间戳之前限制。判断,加约束条件。
            7.约束条件做完,需要加个长度的约束,长度限制为10
            8.当前时间还需要和最后的时间做个比较,求出等待时间
        放回 false  限制
        返回 true  通行
        """
        import time
        ctime = time.time()
        ip = "1.1.1.1"
        if ip not in RECORD:  #如果不在就表示新添加的ip。
            RECORD[ip] = [ctime,]
        else:
            #time_list = [4505461651651,3505461651651,2505461651651,1505461651651,]
            time_list = RECORD[ip]
            while True:
                val = time_list[-1]  #拿到最后一个值
                if (ctime-60) > val: #时间尾端大于最后一个值
                    time_list.pop()  #最后一个给剔除
                else:                #否则正常运行
                    break
            if len(time_list) >10 :
                return False
            time_list.insert(0,ctime)  #添加时间戳,之前需要做判断,加约束条件
        return True

    def wait(self):
        import time
        ctime = time.time()
        first_out_time = RECORD['1.1.1.1'][-1] #取到最后一个时间
        wt = 60 - (ctime - first_out_time) #60秒- (当前时间-第一个出来时间)
        return wt

class LimitView(APIView):
    authentication_classes = []
    permission_classes = []
    throttle_classes = [MyThrottle,]
    def get(self,request,*args,**kwargs):
        self.dispatch
        return Response('控制访问频率示例')
view.py

3.urls.py,(只需要添加标红的)

验证图:

  

调用内部方法实现:

from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.throttling import BaseThrottle,SimpleRateThrottle
from rest_framework import exceptions
# Create your views here.

RECORD = {
    # "1.1.1.1":[150131516161,]
}

#第一种方法。自己写。
class MyThrottle(BaseThrottle): def allow_request(self, request, view): """ Return `True` if the request should be allowed, `False` otherwise. a.对匿名用户进行限制:每个用户1分钟允许访问10次 1.获取用户ip,在request里面。 2.拿到之后,对它进行限制 3.怎么限制? 用一个字典来约束限制 4.如果ip不在字典,就表示新增加的,就加到字典里,以ip为key,时间戳为value。 5.约束条件:一分钟以内的保留,一分钟以外的剔除 6.添加时间戳之前限制。判断,加约束条件。 7.约束条件做完,需要加个长度的约束,长度限制为10 8.当前时间还需要和最后的时间做个比较,求出等待时间 放回 false 限制 返回 true 通行 """ import time ctime = time.time() ip = self.get_ident() if ip not in RECORD: #如果不在就表示新添加的ip。 RECORD[ip] = [ctime,] else: #time_list = [4505461651651,3505461651651,2505461651651,1505461651651,] time_list = RECORD[ip] while True: val = time_list[-1] #拿到最后一个值 if (ctime-60) > val: #时间尾端大于最后一个值 time_list.pop() #最后一个给剔除 else: #否则正常运行 break if len(time_list) >10 : return False time_list.insert(0,ctime) #添加时间戳,之前需要做判断,加约束条件 return True def wait(self): import time ctime = time.time() first_out_time = RECORD[self.get_ident()][-1] #取到最后一个时间 wt = 60 - (ctime - first_out_time) #60秒- (当前时间-第一个出来时间) return wt

#第二种方法,调用内部方法。
class MySimpleRateThrottle(SimpleRateThrottle): scope = 'zxc' def get_cache_key(self, request, view): return self.get_ident(request) class LimitView(APIView): authentication_classes = [] permission_classes = [] throttle_classes = [MySimpleRateThrottle,] def get(self,request,*args,**kwargs): self.dispatch return Response('控制访问频率示例') def throttled(self, request, wait): """ If request is throttled, determine what kind of exception to raise. """ class MyThrottled(exceptions.Throttled): default_detail = '请求被限制.' extra_detail_singular = 'Expected available in {wait} second.' extra_detail_plural = '还需要再等待{wait}' raise MyThrottled(wait)

settings.py:

验证:

  

原文地址:https://www.cnblogs.com/zhongbokun/p/8424356.html