from django.utils.deprecation import MiddlewareMixin
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
from rest_framework.throttling import SimpleRateThrottle
from rest_framework.response import Response
from rest_framework.views import APIView
import time
class Md1(MiddlewareMixin,SimpleRateThrottle):
VISIT_RECORD = {} # 访问者 ip 字典,格式是{ip1:[时间4,时间3,时间2,时间1],ip2:[时间,时间],ip3:[当前时间]}
scope = 'mmy'
def __init__(self,get_response=None):
self.history = None
super().__init__(get_response)
# def process_request(self, request):
# # throttle.allow_request(request, self)
#
# print("Md1请求")
# def process_response(self, request, response):
# print("Md1返回")
# return response
def process_request(self, request ,*args):
print("Md1请求")
"""
Implement the check to see if the request should be throttled.
On success calls `throttle_success`.
On failure calls `throttle_failure`.
"""
# if self.rate is None:
# return True
#
# # self.key = self.get_cache_key(request ,*args)
# if self.key is None:
# return True
self.num_requests=10
self.duration=60
ip = request.META.get('HTTP_ADDR')
self.now = time.time()
if ip not in self.VISIT_RECORD:
self.VISIT_RECORD[ip]=[self.now,]
return
self.history=self.VISIT_RECORD.get(ip)
# self.history = self.cache.get(self.key, [])
# self.history = {ip:[]}
print(type(self.now))
print(type(self.history[-1]),self.history[-1])
# Drop any requests from the history which have now passed the
# throttle duration
while self.history and self.now-self.history[-1] > 60:
self.history.pop()
print('self.history',self.history)
if len(self.history)<self.num_requests:
self.history.insert(0, self.now)
return None
self.VISIT_RECORD[ip]=self.history
print(self.VISIT_RECORD[ip])
msg = 60 - (self.now - self.history[-1])
return HttpResponse(msg)
# def process_response(self, request, response):
# print("Md1返回")
# return response
网友评论