eishit32 commited on
Commit
586dabf
·
verified ·
1 Parent(s): 4d59f18

Create rate_limit.py

Browse files
Files changed (1) hide show
  1. 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)