from django core exceptions import PermissionDenied from collections i

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from django.core.exceptions import PermissionDenied
from collections import deque
import datetime
ips = dict()
VISIT_COUNT = 3
SECONDS_TIMEOUT = 20
class FilterNumberRequests:
def __init__(self, get_response):
self.get_response = get_response
self.count = 0
def __call__(self, request):
now = datetime.datetime.now()
check_time = now - datetime.timedelta(seconds=SECONDS_TIMEOUT)
ip = request.META.get('REMOTE_ADDR')
visits = ips.get(ip, deque([], VISIT_COUNT))
visits.append(now)
ips[ip] = visits
if visits[0] >= check_time and len(visits) == VISIT_COUNT:
raise PermissionDenied
response = self.get_response(request)
return response