系统中有时候需要限定人员请求流量和课允许访问IP来保障系统稳定性和不被黑客攻击,者就需要对访问ip进行判断和限制,阻止恶意请求访问电脑。
提示:以下是本篇文章正文内容,下面案例可供参考
manage.py runserver 0.0.0.0:8000
ALLOWED_HOSTS="*"
或ALLOWED_HOSTS=["192.168.1.1","127.0.0.1"]
class Host_info(models.Model):
host = models.CharField(max_length=32)
count = models.IntegerField()
start_time = models.DateTimeField()
is_lock = models.CharField(max_length=32,default='2')
参数介绍
host
:记录主机ipcount
:记录请求的次数start_time
:记录请求的时间is_lock
:记录该ip的状态,默认为2 2代表未锁定,1代表锁定from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import render, HttpResponse
from app01 import models
import datetime
class Md1(MiddlewareMixin):
def process_request(self, request):
url = request.path
if url.startswith('/favicon.ico'):
return HttpResponse
class Md2(MiddlewareMixin):
def process_request(self, request):
now_time = datetime.datetime.now()
host = request.META.get('REMOTE_ADDR')
ret = models.Host_info.objects.filter(host=host).first()
if ret:
aa = now_time - ret.start_time
if aa.seconds >= 60:
ret.count = 1
ret.start_time = now_time
ret.is_lock = '2'
ret.save()
return None
if aa.seconds < 60 and ret.is_lock == '1':
return HttpResponse('登陆次数频繁,一分钟后再试')
if ret.count < 4 and ret.is_lock == '2':
if ret.count == 2:
ret.is_lock = '1'
ret.count = 0
ret.save()
else:
ret.count += 1
ret.start_time = now_time
ret.save()
return None
else:
models.Host_info.objects.create(host=host, start_time=now_time, count=1)
return None
添加两行代码在MIDDLEWARE列表中:
'mymiddleware.Md1',
'mymiddleware.Md2',
并配置下面两句,设置时区
TIME_ZONE = 'Asia/Shanghai'
USE_TZ = False