model:
class LoginModel(models.Model):
username = models.CharField(max_length=32)
password = models.CharField(max_length=32)
type_choice = (
(0, "普通用户"),
(1, "VIP"),
(2, "SVIP"),
)
user_type = models.IntegerField(choices=type_choice)
ip_addr = models.CharField(max_length=32)
visits = models.IntegerField()
def __str__(self):
return self.username
自定义类
LOGIN_CODE = {}
class FrequencyThrottles:
def allow_request(self, request, view):
ip_addr = request.META.get("REMOTE_ADDR")
if ip_addr:
models.LoginModel.objects.filter(ip_addr=ip_addr).update(visits=F("visits") + 1)
visit_times = models.LoginModel.objects.filter(username=request.user).first().visits
if ip_addr not in LOGIN_CODE:
LOGIN_CODE[ip_addr] = {}
if not LOGIN_CODE[ip_addr]:
LOGIN_CODE[ip_addr]["limit_time"] = datetime.datetime.now() + datetime.timedelta(seconds=60)
LOGIN_CODE[ip_addr]["visit_times"] = visit_times + 10
LOGIN_CODE[ip_addr]["blacklist"] = []
elif datetime.datetime.now() <= LOGIN_CODE[ip_addr]["limit_time"] and visit_times >= LOGIN_CODE[ip_addr][
"visit_times"] and ip_addr not in LOGIN_CODE[ip_addr]["blacklist"]:
LOGIN_CODE[ip_addr]["blacklist"].append(ip_addr)
if datetime.datetime.now() > LOGIN_CODE[ip_addr]["limit_time"] :
LOGIN_CODE[ip_addr] = {}
if ip_addr not in LOGIN_CODE[ip_addr].get("blacklist", []):
return True
else:
return False
def wait(self):
pass