「Django」rest_framework学习系列-节流控制

1、节流自定义类:

import time
from api import models

VISIT_RECORD = {}

class VisitThrottle(BaseThrottle):
    #设置访问频率为60秒3次
    def allow_request(self, request, view):
        #获取用户ID
        # remote_addr = request.META.get('REMOTE_ADDR')
        remote_addr = self.get_ident(request)
        ctime = time.time()
        if remote_addr not in VISIT_RECORD:
            VISIT_RECORD[remote_addr] = [ctime]
        history = VISIT_RECORD.get(remote_addr)
        self.history = history
        while history and history[-1] < ctime-60:
            history.pop()

        if len(history) < 3:
            history.insert(0,ctime)
            return True

    def wait(self):
        ctime = time.time()
        wtime = 60 - (ctime-self.history[-1])
        return wtime
View Code

2、内置节流类
a.项目下utils文件throttle.py文件:

from rest_framework.throttling import SimpleRateThrottle

#对匿名用户的限制
class VisitThrottle(SimpleRateThrottle):
    scope = 'none' #限制规则写在settings全局配置里
    def get_cache_key(self, request, view):
        return self.get_ident(request)

#对注册用户的限制
class UserThrottle(SimpleRateThrottle):
    scope = 'user'
    def get_cache_key(self, request, view):
        return request.user.username
View Code

b.settings配置用户全局认证如下:

'DEFAULT_THROTTLE_CLASSES':['api.utils.throttle.VisitThrottle',], #节流认证
'DEFAULT_THROTTLE_RATES':{
'none':'3/m',
'user':'10/m',
},

c.views业务类可以在全局认证外设置单独认证规则:

throttle_classes = []
原文地址:https://www.cnblogs.com/wrxblog/p/10402559.html