Django 限制用户访问频率的中间件的实现

时间:2022-09-05 12:14:53

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

common/middleware.py

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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:]

二、将中间件加入配置文件

setting.py

?
1
2
3
4
5
6
7
8
9
10
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',
]

对使用 rest_framework 框架的项目来说,可以使用框架的设置来对api的访问频率进行限制

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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'
# }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://segmentfault.com/a/1190000016114237