Django—限制用户访问频率

django中间件 一、定义限制访问频率的中间件

  • common/middleware.py
import timefrom django.utils.deprecation import MiddlewareMixinMAX_REQUEST_PER_SECOND=2 #每秒访问次数class RequestBlockingMiddleware(MiddlewareMixin):def process_request(self,request): now=time.time() request_queue = request.session.get('request_queue',[]) if len(request_queue) < MAX_REQUEST_PER_SECOND: request_queue.append(now) request.session['request_queue']=request_queue else: time0=request_queue[0] if (now-time0)<1: time.sleep(5)request_queue.append(time.time()) request.session['request_queue']=request_queue[1:]

二、将中间件加入配置文件
  • setting.py
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'common.middleware.RequestBlockingMiddleware', #在sessions之后,auth之前 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]12345678910

drf的throttle设置api的访问速率
作用:防止爬虫无节制的爬取数据 减少服务器的压力。
drf的自带功能
【Django—限制用户访问频率】官方文档:http://www.django-rest-framew...
一、throttle配置到setting中
'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ), 'DEFAULT_THROTTLE_RATES': { 'anon': '100/day', 'user': '1000/day' }

限速规则与限速的类。未登录情况下限速,通过ip地址。登录情况下通过session或token来判断。
The rate descriptions used in DEFAULT_THROTTLE_RATES may include second, minute, hour or day as the throttle period.
二、设置到我们的接口
from rest_framework.throttling import UserRateThrottle,AnonRateThrottlethrottle_classes = (UserRateThrottle, AnonRateThrottle)

在throttling的源码中
parse_rate:进行解析我们的规则
allow_request:中使用django的cache进行缓存。将每个ip的访问次数设置到缓存中
get_ident:会通过 request.meta.get('remote_addr')取出ip
已登录用户的限制是通过 request.user.pk

    推荐阅读