1.在子应用目录下创建黑白名单中间件文件 web_secure.py ,内容为:
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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| from django.utils.deprecation import MiddlewareMixin from django.http import HttpResponse import time
white = ['127.0.0.1'] black = ['127.0.0.2'] ban = {} ban_seconds = 3 ban_limit = 5 ban_time = 30
class White_Black(MiddlewareMixin): def process_request(self, request):
ip = str(request.META.get('REMOTE_ADDR'))
if ip in black: return HttpResponse('禁止访问', status=403)
if not ban.get(ip): ban[ip] = {'total': 1, 'time': int(time.time()), "banTime":''}
print(ip, ban[ip].get('total'))
if ban[ip]['time'] + ban_seconds > int(time.time()):
if ban[ip]['total'] > ban_limit: ban[ip]['banTime'] = int(time.time()) + ban_time return self.ban_response()
ban[ip]['total'] += 1 print(ban)
else: limit_timie = ban[ip]['banTime']
if limit_timie and limit_timie > int(time.time()): return self.ban_response()
del ban[ip]
def ban_response(self): return HttpResponse(f'访问过于频繁,请 {ban_time} 秒后重试!!')
def process_response(self, request, resonse): return resonse
|
2.编辑 django 项目主包目录下的 settings.py 文件,在 MIDDLEWARE = […] 配置列表中注册自定义的中间件类名,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13
| MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'users.middlewarse.MD1', 'users.middlewarse.MD2', 'users,web_secure,White_Black', ]
|
3.测试。在浏览器中输入 url: http://192.168.3.254:8001/users/register/ (注意:这里的IP 和 任意路由根据自己的实际情况进行修改),效果如下:
3.1.正常访问:
3.2.快速刷新,访问: