2019-07-30 14:20:08 1271瀏覽
今天千鋒扣丁學(xué)堂Python培訓(xùn)老師給大家分享一篇關(guān)于django基于中間件實(shí)現(xiàn)限制ip頻繁訪問過程詳解,首先瀏覽器前端傳來的請求,必須通過中間件,才能到后面路由,視圖函數(shù),所以我們在中間件那里做一層處理,我們還需要知道是哪個(gè)ip,在什么時(shí)候,請求了幾次,這些數(shù)據(jù)是要知道,并且記錄下來,所以我創(chuàng)建了一個(gè)表,來存放這些信息數(shù)據(jù),下面我們一起來看一下吧。
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')
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('登陸次數(shù)頻繁,一分鐘后再試') 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
'mymiddleware.Md1', 'mymiddleware.Md2',
TIME_ZONE = 'Asia/Shanghai' USE_TZ = False
## 代碼其實(shí)很簡單,主要是邏輯處理,你是怎么想就用代碼去實(shí)現(xiàn)。 ## 對了,這里的數(shù)據(jù)存儲,你可以定義一個(gè)變量去存放存這些信息(也就是我數(shù)據(jù)表存放的這個(gè)) ## 這里唯一值得注意的就是時(shí)間了,你要很清楚知道時(shí)區(qū)這個(gè)問題。
aa = now_time - ret.start_time aa.seconds # 取到相差多少秒
【關(guān)注微信公眾號獲取更多學(xué)習(xí)資料】 【掃碼進(jìn)入Python全棧開發(fā)免費(fèi)公開課】
查看更多關(guān)于"Python開發(fā)資訊"的相關(guān)文章>