Spaces:
Sleeping
Sleeping
Create rate_limit.py
Browse files- rate_limit.py +28 -0
rate_limit.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
from fastapi import HTTPException
|
| 3 |
+
|
| 4 |
+
# Request memory
|
| 5 |
+
RATE_LOG = {}
|
| 6 |
+
|
| 7 |
+
def rate_limiter(key: str, limit: int, window: int = 60):
|
| 8 |
+
"""
|
| 9 |
+
key = api key
|
| 10 |
+
limit = requests allowed
|
| 11 |
+
window = time window (seconds)
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
now = int(time.time())
|
| 15 |
+
|
| 16 |
+
if key not in RATE_LOG:
|
| 17 |
+
RATE_LOG[key] = []
|
| 18 |
+
|
| 19 |
+
# Remove old requests
|
| 20 |
+
RATE_LOG[key] = [t for t in RATE_LOG[key] if now - t < window]
|
| 21 |
+
|
| 22 |
+
if len(RATE_LOG[key]) >= limit:
|
| 23 |
+
raise HTTPException(
|
| 24 |
+
status_code=429,
|
| 25 |
+
detail="Rate limit exceeded. Upgrade plan."
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
RATE_LOG[key].append(now)
|