Update api/rpmlimits.py
Browse files- api/rpmlimits.py +26 -24
api/rpmlimits.py
CHANGED
@@ -1,42 +1,44 @@
|
|
1 |
-
import
|
2 |
-
from datetime import timedelta
|
3 |
-
import redis
|
4 |
from fastapi import HTTPException, Request
|
5 |
-
from dotenv import load_dotenv
|
6 |
from api.logger import setup_logger
|
|
|
|
|
7 |
|
8 |
load_dotenv()
|
9 |
logger = setup_logger(__name__)
|
10 |
|
11 |
-
# Initialize Redis connection
|
12 |
-
REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
|
13 |
-
REDIS_PORT = int(os.getenv("REDIS_PORT", 6379))
|
14 |
-
redis_client = redis.StrictRedis(host=REDIS_HOST, port=REDIS_PORT, decode_responses=True)
|
15 |
-
|
16 |
# Set request limit per minute from environment variable
|
17 |
REQUEST_LIMIT_PER_MINUTE = int(os.getenv("REQUEST_LIMIT_PER_MINUTE", "10"))
|
18 |
|
|
|
|
|
|
|
19 |
def get_client_ip(request: Request) -> str:
|
20 |
"""Retrieve the IP address of the client making the request."""
|
21 |
return request.client.host
|
22 |
|
23 |
def check_rate_limit(ip: str):
|
24 |
"""Check if the IP has exceeded the request limit per minute."""
|
25 |
-
|
26 |
-
current_count = redis_client.get(redis_key)
|
27 |
|
28 |
-
if
|
29 |
-
# New IP, initialize with a count and set
|
30 |
-
|
31 |
logger.info(f"New IP {ip} added to request counts.")
|
32 |
else:
|
33 |
-
|
34 |
-
if
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import datetime, timedelta
|
|
|
|
|
2 |
from fastapi import HTTPException, Request
|
|
|
3 |
from api.logger import setup_logger
|
4 |
+
import os
|
5 |
+
from dotenv import load_dotenv
|
6 |
|
7 |
load_dotenv()
|
8 |
logger = setup_logger(__name__)
|
9 |
|
|
|
|
|
|
|
|
|
|
|
10 |
# Set request limit per minute from environment variable
|
11 |
REQUEST_LIMIT_PER_MINUTE = int(os.getenv("REQUEST_LIMIT_PER_MINUTE", "10"))
|
12 |
|
13 |
+
# Dictionary to track IP addresses and request counts
|
14 |
+
request_counts = {}
|
15 |
+
|
16 |
def get_client_ip(request: Request) -> str:
|
17 |
"""Retrieve the IP address of the client making the request."""
|
18 |
return request.client.host
|
19 |
|
20 |
def check_rate_limit(ip: str):
|
21 |
"""Check if the IP has exceeded the request limit per minute."""
|
22 |
+
current_time = datetime.now()
|
|
|
23 |
|
24 |
+
if ip not in request_counts:
|
25 |
+
# New IP, initialize with a count and set the timestamp
|
26 |
+
request_counts[ip] = {"count": 1, "timestamp": current_time}
|
27 |
logger.info(f"New IP {ip} added to request counts.")
|
28 |
else:
|
29 |
+
ip_data = request_counts[ip]
|
30 |
+
# Check if the timestamp is more than a minute old
|
31 |
+
if current_time - ip_data["timestamp"] < timedelta(minutes=1):
|
32 |
+
# If within the same minute, increment the count
|
33 |
+
ip_data["count"] += 1
|
34 |
+
logger.info(f"IP {ip} made request number {ip_data['count']}.")
|
35 |
+
if ip_data["count"] > REQUEST_LIMIT_PER_MINUTE:
|
36 |
+
logger.warning(f"Rate limit exceeded for IP {ip}.")
|
37 |
+
raise HTTPException(
|
38 |
+
status_code=429,
|
39 |
+
detail={"error": {"message": "Rate limit exceeded. Please wait and try again.", "type": "rate_limit"}},
|
40 |
+
)
|
41 |
+
else:
|
42 |
+
# If more than a minute has passed, reset the count and timestamp
|
43 |
+
request_counts[ip] = {"count": 1, "timestamp": current_time}
|
44 |
+
logger.info(f"Request count reset for IP {ip}.")
|