Files

45 lines
1.5 KiB
Python
Raw Permalink Normal View History

2024-10-06 17:14:16 +08:00
from typing import Dict, Union
from datetime import datetime, timedelta
from fastapi import HTTPException, Request
class IPRateLimit:
def __init__(self, count: int, minutes: int):
self.ips: Dict[str, Dict[str, Union[int, datetime]]] = {}
self.count = count
self.minutes = minutes
def check_ip(self, ip: str) -> bool:
if ip in self.ips:
ip_info = self.ips[ip]
2025-02-15 22:00:53 +08:00
if ip_info["count"] >= self.count:
if ip_info["time"] + timedelta(minutes=self.minutes) > datetime.now():
2024-10-06 17:14:16 +08:00
return False
self.ips.pop(ip)
return True
def add_ip(self, ip: str) -> int:
2025-02-15 22:00:53 +08:00
ip_info = self.ips.get(ip, {"count": 0, "time": datetime.now()})
ip_info["count"] += 1
ip_info["time"] = datetime.now()
2024-10-06 17:14:16 +08:00
self.ips[ip] = ip_info
2025-02-15 22:00:53 +08:00
return ip_info["count"]
2024-10-06 17:14:16 +08:00
async def remove_expired_ip(self) -> None:
now = datetime.now()
expiration = timedelta(minutes=self.minutes)
2025-02-15 22:00:53 +08:00
self.ips = {
ip: info
for ip, info in self.ips.items()
if info["time"] + expiration >= now
}
2024-10-06 17:14:16 +08:00
def __call__(self, request: Request) -> str:
2025-02-15 22:00:53 +08:00
ip = (
request.headers.get("X-Real-IP")
or request.headers.get("X-Forwarded-For")
or request.client.host
)
2024-10-06 17:14:16 +08:00
if not self.check_ip(ip):
raise HTTPException(status_code=423, detail="请求次数过多,请稍后再试")
return ip