由于Http请求是无状态的,服务端能直知道是那个客户端的访问,所以,我们可以利用session技术,记住每个用户访问的状态数据。
- 在用户发起请求后,记录用户IP, 同时进行每次访问时间的统计,实现客户端的访问频率限制,IP禁止。
import time
from django.http import HttpResponse
# Create your views here.
VISIT_LIMIT = 20
TIME_INTERVAL = 10
RETRY_TIME = 10
IP_BLACKLIST = ["192.168.1.2", "127.0.0.1"]
class LimitMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# 处理请求前(url匹配前)调用
# Code to be executed for each request before
# the view (and later middleware) are called.
now = time.time()
print("处理请求前(url匹配前)调用",now)
request_queue