rest_framework-节流-总结完结篇

列表从后往前读#1.在request中获取IP#2.访问记录VISIT_RECORD = {}  放缓存 数据库 均可以 建议缓存import timeclass VisitThrottle(object):    """10s内只能访问3次"""    def __init__(self):        self.history = None    def allow_request(self, request, view):    #1.在request中获取IP    #2.访问记录        #remote_addr = request._request.META.get('REMOTE_ADDR')        remote_addr = request.META.get("REMOTE_ADDR")  #均可以        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 - 10:            history.pop()        if len(history) < 3:            history.insert(0, ctime)            return True        return True #表示能够继续访问        #return False #访问频率过高,被限制    def wait(self):    """还须要等多少秒"""        ctime = time.time()        data = 60 - (ctime - self.history[-1])        return datathrottle_classes = [VisitThrottle,]#全局配置REST_FRAMEWORK = {    "DEFAULT_THROTTLE_CLASSES":['api.utils.throttle.VisitThrottle']}源码流程    check_throttles    self.get_throttles内置函数from rest_framework.throttling import BaseThrottleclass BaseThrottle(object):    def allow_request(self,request, view)  #由这个函数进行触发    def get_ident(self,request):    def wait(self):到时可使用SimpleRateThrottlefrom rest_framework.throttling import SimpleRateThrottleclass VisiThrottle(SimpleRateThrottle):    scope = "xiao" #当KEY使用 当在setting设置DEFAULT_THROTTLE_RATES : {"xiao":'3/m'}  m分 h时 d天    def get_cache_key(self, request, view):        return request.META.get("REMOTE_ADDR")class VIPThrottle(SimpleRateThrottle):    scope = "vip" #当KEY使用 当在setting设置DEFAULT_THROTTLE_RATES : {"xiao":'3/m'}  m分 h时 d天    def get_cache_key(self, request, view):        return request.user.username  #认证时的对象的usernameSettings里面添加REST_FRAMEWORK = {    "DEFAULT_THROTTLE_CLASSES":['cmdb.utils.throttle.Visit2Throttle'],  #此时不能在这里添加两个控制    "DEFAULT_THROTTLE_RATES": {    "xiao": '3/m',    "vip":'10/m', #vip用户访问频率限制}}基本使用    类   继承:BaseThrottle 实现:allow_request, wait    类   继承:SimpleRateThrottle 实现:get_cache_key 、 scope = "xiao" (配置文件中的key)
相关文章
相关标签/搜索