过于频繁访问伺服器,会造成伺服器负担,这时必须使用middleware来阻挡,在尚未访问到资料前,就阻挡
创建一个资料夹middleware与app同级
middleware底下创建mymiddleware.py
mymiddleware.py
from django.core.cache import cachefrom django.http import HttpResponsefrom django.utils.deprecation import MiddlewareMixinclass MyMiddleware(MiddlewareMixin): def process_request(self, request): ip = request.META.get('REMOTE_ADDR') if request.path == '/app/test/': result = cache.get(ip) if result: return HttpResponse('请10秒后在试') cache.set(ip, ip, timeout=10)
setting.py注册自订的middleware
MIDDLEWARE = [ 'middleware.mymiddleware.MyMiddleware',
单纯的静态网页比较不需要什么加载时间,对伺服器消耗也较少,但是如果试搜寻可能消耗就会比较多
def process_request(self, request):是固定用法
request.META打印出来会是许多关于网页的资讯,像是'REMOTE_ADDR',CONTENT_TYPE,user-agent...
request.path要的是需要添加黑名单的网址(不是所有网页都需要黑名单),也就是127.0.0.1:8000后面的那串
那更好的方法是一分钟不能访问超过n次,因为使用者总是会觉得加载速度很慢,就一直刷新
一开始先确定该ip是否有来访问过
没有就为该ip建一个阵列,来存取时间(time.time())
有就使用快取上纪录ip的arr,
当现在时间减去阵列中的时间,大于60就会将阵列的值pop出来
if request.path == '/app/test/': arr = [] if cache.get(ip): arr = cache.get(ip) while arr and time.time()-arr[-1] > 60: arr.pop() arr.append(time.time()) cache.set(ip, arr, timeout=60) print(arr) if len(arr) > 10: return HttpResponse('请求过于频繁,请一分钟后在试')
在新增一些东西就变成黑名单啦
一开始不知道是否有黑名单在快取中,所以要先创建一个black_list,如果有就用原有的black_list
if len(arr) > 20:
black_list.append(ip)
cache.set('black_list', black_list, timeout=60*10)
如果已经告知"请求过于频繁,请一分钟后在试",还是继续访问,就会将该ip添加到黑名单中
if request.path == '/app/test/': black_list = [] if cache.get('black_list'): black_list = cache.get('black_list') if ip in black_list: return HttpResponse('10分钟禁止访问') arr = [] if cache.get(ip): arr = cache.get(ip) while arr and time.time()-arr[-1] > 60: arr.pop() arr.append(time.time()) cache.set(ip, arr, timeout=60) if len(arr) > 20: black_list.append(ip) cache.set('black_list', black_list, timeout=60*10) print(arr) if len(arr) > 10: return HttpResponse('请求过于频繁,请一分钟后在试')