Django——对IP访问频率进行限制
程序员文章站
2022-06-14 19:52:13
...
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',
]