1.创建model
class BlackList(models.Model):
username = models.CharField(max_length=30,unique=True)
net_ip = models.CharField(max_length=40)
lock_time = models.IntegerField(default=3600)
class Meta:
index_together = ['username', 'net_ip']
unique_together = ['username', 'net_ip']
# 联合索引要这样写入!!!!!!!!!
db_table = 'black_list'
2.在我们创建的方法里面生成一个中间件
import redis
r = redis.Redis(host='127.0.0.1', port=6379, db=6)
class VisitInfoRedisMiddleWare(MiddlewareMixin):
def process_request(self,request):
username=request.GET.get('username')
print(username,741741)
if request.path == '/user/dingding/':
# 获取客户端的ip
if "HTTP_X_FORWARDED_FOR" in request.META:
net_ip = request.META.get("HTTP_X_FOGWARDED_FOR")
else:
net_ip = request.META.get("REMOTE_ADDR")
# 检测是否已在黑名单
blacklist = BlackList.objects.filter(username=username, net_ip=net_ip).first()
if blacklist:
return HttpResponse(json.dumps({'code': 201, 'msg': '已被列入黑名单'}, ensure_ascii=False))
if r.get(net_ip):
num = r.incrby(net_ip) # 在验证码有效期内,连续访问时 +1
num = r.get(net_ip).decode()
print(num)
if int(num)>=3: # 在验证码有效期内 连续访问大于等于3次 加入黑名单
blacklist = BlackList(net_ip=net_ip,username=username)
blacklist.save()
return HttpResponse(json.dumps({'code': 201, 'msg': '中间件检测验证码在有效期'}, ensure_ascii=False))
else:
# 将ip当作键存入redis,有效期60秒
r.setex(net_ip, 60,1)
3.在setting中的middleware调用中间件方法
'user.utils.process.VisitInfoRedisMiddleWare',
地址+我们自己创建的中间件方法名字