• 「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 = []
  • 相关阅读:
    生成更大的陆地 Making A Large Island
    HDU 3342 Legal or Not【拓扑排序】
    POJ 2367 Genealogical tree【拓扑排序】
    CodeForces Round #290 Div.2
    HDU 1010 Tempter of the Bone【DFS】
    HDU 1312 Red and Black【DFS】
    POJ 1664 放苹果【DFS】
    HDU 1587 Flowers【贪心】
    Codeforces Round #289 Div 2
    HDU 1241 Oil Deposits【DFS】
  • 原文地址:https://www.cnblogs.com/wrxblog/p/10402559.html
Copyright © 2020-2023  润新知