Django REST framework之throttle节流原理

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.throttling import BaseThrottle,SimpleRateThrottle

from rest_framework import exceptions

RECORD = {

}
class MyThrottle(BaseThrottle):
    def allow_request(self,request,view):
        """
        # 返回False,限制
        # 返回True,通行
        :param request: 
        :param view: 
        :return: 
        """
        """
         a. 对匿名用户进行限制:每个用户1分钟允许访问10次
            - 获取用户IP request 112.122.221.122
        """
        import time
        ctime = time.time()
        ip = self.get_ident()
        if ip not in RECORD:
            RECORD[ip] = [ctime,]
        else:
            # [4507862389234,3507862389234,2507862389234,1507862389234,]
            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_in_time = RECORD[self.get_ident()][-1]
        wt = 60 - (ctime - first_in_time)
        return wt


class MySimpleRateThrottle(SimpleRateThrottle):
    scope = "zClass"

    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)


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值