码迷,mamicode.com
首页 > 其他好文 > 详细

中间件控制访问评率

时间:2018-11-15 18:33:21      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:from   请求   attr   get   mon   csrf   sage   csr   process   

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()

 

中间件控制访问评率

标签:from   请求   attr   get   mon   csrf   sage   csr   process   

原文地址:https://www.cnblogs.com/yidashi110/p/9964982.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!