功能:10次请求则禁止访问,30次请求则拉黑1天
原理:利用列表存储每个ip的请求时间戳,如果请求60秒内请求次数 > 10,禁止访问,>30则拉黑
AOP代码
import time
from django.core.cache import cache
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
class DePaMiddleware(MiddlewareMixin):
def process_request(self, request):
if request.path == "/index/":
ip = request.META.get("REMOTE.ADDR")
requests = cache.get(ip, [])
while requests and time.time() - requests[-1] > 60:
requests.pop()
if len(requests) >= 10:
return HttpResponse("你被拦截了")
requests.insert(0, time.time())
cache.set(ip, requests, timeout=60)
class DePaMiddleware(MiddlewareMixin):
def process_request(self, request):
if request.path == "/index/":
ip = request.META.get("REMOTE.ADDR")
black_list = cache.get("blackList", [])
if ip in black_list:
return HttpResponse("黑名单用户,凉凉")
requests = cache.get(ip, [])
print(requests)
while requests and time.time() - requests[-1] > 60:
requests.pop()
requests.insert(0, time.time())
cache.set(ip, requests, timeout=60)
if len(requests) > 30:
black_list.append(ip)
cache.set("blackList",black_list,timeout=60*60*24)
return HttpResponse("你被拉黑了")
if len(requests) >= 10:
return HttpResponse("你被拦截了")