应用案例
1.做IP访问频率限制
某些IP访问服务器的频率过高,进行拦截, 比如每分钟不能超过20次
2.URL访问过滤
如果用户访问的是login视图,就允许请求
如果访问其他视图, 需要检测是不是有session认证, 已经有了放行, 没有返回login,这样就不用在多个视图上写装饰器了,(添加白名单与黑名单)
限制访问请求次数的中间件简单实现
from django.utils.deprecation import MiddlewareMixin from django.shortcuts import HttpResponse, redirect, render from django.urls import reverse class SessionAuth(MiddlewareMixin): # __count = 0 def process_request(self, request): # print('session_认证') path = request.path # print('path>>>',path) # 白名单 allow_pass_urls = [reverse('login'), ] # print('allow_pass_urls',allow_pass_urls) if path in allow_pass_urls: self.__count = 0 return None else: ret = request.session.get('session_login') if ret: # username = request.session.get('user') # self.__count += 1 # if self.__count >= 5: # request.session.flush() # return HttpResponse('丫请求的次数过多,滚犊子') return None else: return redirect(reverse('login')) # return HttpResponse('ok') def process_response(self, request, response): # print('session_认证响应') return response def process_response(self, request, response): return response