文章目录
- 前言
- 一、Django项目设置可请求IP
- 二、Django项目中间件实现限制ip频繁访问
- 1.models文件
- 2.mymiddleware自定义中间件文件
- 3.settings文件
前言
系统中有时候需要限定人员请求流量和课允许访问IP来保障系统稳定性和不被黑客攻击,者就需要对访问ip进行判断和限制,阻止恶意请求访问电脑。
提示:以下是本篇文章正文内容,下面案例可供参考
一、Django项目设置可请求IP
- 首先需要执行>
manage.py runserver 0.0.0.0:8000
- 在setting.py里面需要添加
ALLOWED_HOSTS="*"
或ALLOWED_HOSTS=["192.168.1.1","127.0.0.1"]
二、Django项目中间件实现限制ip频繁访问
1.models文件
代码语言:javascript复制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代表锁定
2.mymiddleware自定义中间件文件
代码语言:javascript复制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
3.settings文件
添加两行代码在MIDDLEWARE列表中:
代码语言:javascript复制'mymiddleware.Md1',
'mymiddleware.Md2',
并配置下面两句,设置时区
代码语言:javascript复制TIME_ZONE = 'Asia/Shanghai'
USE_TZ = False