中间件控制访问评率

setings设置

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'mymiddleware.s1.Throttle',  # 自定义中间件
]
ACCESS_LIMIT = 10

 

自定义中间件

from django.conf import settings

ACCESS_RECORD = {} # 自定义访问频率限制的中间件 class Throttle(MiddlewareMixin): def process_request(self, request): access_limit = settings.ACCESS_LIMIT if hasattr(settings, 'ACCESS_LIMIT') else 60 # 当前请求的IP地址 ip = request.META.get('REMOTE_ADDR') if ip not in ACCESS_RECORD: ACCESS_RECORD[ip] = [] history = ACCESS_RECORD[ip] # 判断最近的10秒钟之内这个IP访问次数是否大于3 now = time.time() # DRF 访问频率限制 while history and now - history[-1] > access_limit: history.pop() history.insert(0, now) if len(history) > 3: return HttpResponse('')

 

posted @ 2018-11-15 17:38  从入门到出师  阅读(177)  评论(0编辑  收藏  举报