Posted in Python onAugust 30, 2019
REST_FRAMEWORK 配置
对使用 rest_framework 框架的项目来说,可以使用框架的设置来对api的访问频率进行限制
REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( # 'lecare.core.rest_auth.CrossSiteSessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ # 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.AllowAny', ], 'PAGE_SIZE': 20, 'UNICODE_JSON': False, # 'COERCE_DECIMAL_TO_STRING': False, # 'EXCEPTION_HANDLER': 'lecare.core.custom_exception_handler.custom_exception_handler', 'JWT_EXPIRATION_DELTA': datetime.timedelta(hours = 2), 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days = 360), 'JWT_ALLOW_REFRESH': False, 'JWT_AUTH_HEADER_PREFIX': 'JWT', 'JWT_PAYLOAD_HANDLER': 'consumer.jwt_conf.jwt_payload_handler', 'JWT_RESPONSE_PAYLOAD_HANDLER': 'consumer.jwt_conf.jwt_response_payload_handler', 'JWT_GET_USER_SECRET_KEY': 'consumer.jwt_conf.jwt_get_secret_key', # 'DEFAULT_THROTTLE_CLASSES': ( # # 开启匿名用户接口请求频率限制 # 'rest_framework.throttling.AnonRateThrottle', # # 开启授权用户接口请求频率限制 # 'rest_framework.throttling.UserRateThrottle' # ), # 'DEFAULT_THROTTLE_RATES': { # # 频率限制有second, minute, hour, day # # 匿名用户请求频率 # 'anon': '30/second', # # 授权用户请求频率 # 'user': '30/second' # } }
使用middleware中间件来限制IP频率
import time from django.utils.deprecation import MiddlewareMixin MAX_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:] #启用RequestBlocking中间件 IDDLEWARE = [ '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', ]
以上这篇Django 对IP访问频率进行限制的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。
Django 对IP访问频率进行限制的例子
- Author -
何惜戈声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@