Bahodir Nematjonov commited on
Commit
73ef21f
·
1 Parent(s): 1392014

feat: Rate Limiter

Browse files
Files changed (1) hide show
  1. main.py +21 -4
main.py CHANGED
@@ -12,7 +12,9 @@ import os
12
  import logging
13
  from dotenv import load_dotenv
14
 
 
15
  load_dotenv()
 
16
  # Import SlowAPI for Rate Limiting
17
  from slowapi import Limiter, _rate_limit_exceeded_handler
18
  from slowapi.util import get_remote_address
@@ -20,21 +22,37 @@ from slowapi.middleware import SlowAPIMiddleware
20
 
21
  logging.basicConfig(level=logging.INFO)
22
 
23
- SECRET_KEY = os.getenv("SECRET_KEY")
24
- REFRESH_SECRET_KEY = os.getenv("REFRESH_SECRET_KEY")
 
25
  ALGORITHM = "HS256"
26
  ACCESS_TOKEN_EXPIRE_MINUTES = 30
27
  REFRESH_TOKEN_EXPIRE_DAYS = 7
28
 
29
  app = FastAPI()
30
 
 
 
 
 
 
 
 
31
  # Initialize Rate Limiter
32
- limiter = Limiter(key_func=get_remote_address)
33
  app.state.limiter = limiter
34
 
35
  # Attach Rate Limit Exceeded Handler
36
  app.add_exception_handler(429, _rate_limit_exceeded_handler)
37
 
 
 
 
 
 
 
 
 
38
  # Add Middleware for Rate Limiting
39
  app.add_middleware(SlowAPIMiddleware)
40
 
@@ -99,7 +117,6 @@ async def generate(
99
  query_input: QueryInput,
100
  username: str = Depends(verify_access_token),
101
  stream: bool = Query(False, description="Enable streaming response"),
102
-
103
  ):
104
  """Handles both streaming and non-streaming responses, with shutdown detection."""
105
  if shutdown_event.is_set():
 
12
  import logging
13
  from dotenv import load_dotenv
14
 
15
+ # Load environment variables
16
  load_dotenv()
17
+
18
  # Import SlowAPI for Rate Limiting
19
  from slowapi import Limiter, _rate_limit_exceeded_handler
20
  from slowapi.util import get_remote_address
 
22
 
23
  logging.basicConfig(level=logging.INFO)
24
 
25
+ # Security Keys with Default Fallbacks
26
+ SECRET_KEY = os.getenv("SECRET_KEY", "default_fallback_256_bit_key")
27
+ REFRESH_SECRET_KEY = os.getenv("REFRESH_SECRET_KEY", SECRET_KEY)
28
  ALGORITHM = "HS256"
29
  ACCESS_TOKEN_EXPIRE_MINUTES = 30
30
  REFRESH_TOKEN_EXPIRE_DAYS = 7
31
 
32
  app = FastAPI()
33
 
34
+ # Custom Key Function for Rate Limiting (Handles Proxies)
35
+ def custom_key_func(request: Request):
36
+ forwarded = request.headers.get("X-Forwarded-For")
37
+ if forwarded:
38
+ return forwarded.split(",")[0] # Get real client IP if behind proxy
39
+ return get_remote_address(request)
40
+
41
  # Initialize Rate Limiter
42
+ limiter = Limiter(key_func=custom_key_func)
43
  app.state.limiter = limiter
44
 
45
  # Attach Rate Limit Exceeded Handler
46
  app.add_exception_handler(429, _rate_limit_exceeded_handler)
47
 
48
+ # Custom Rate Limit Response
49
+ @app.exception_handler(429)
50
+ async def rate_limit_exceeded_handler(request: Request, exc):
51
+ return JSONResponse(
52
+ status_code=429,
53
+ content={"error": "Rate limit exceeded. Please try again later."}
54
+ )
55
+
56
  # Add Middleware for Rate Limiting
57
  app.add_middleware(SlowAPIMiddleware)
58
 
 
117
  query_input: QueryInput,
118
  username: str = Depends(verify_access_token),
119
  stream: bool = Query(False, description="Enable streaming response"),
 
120
  ):
121
  """Handles both streaming and non-streaming responses, with shutdown detection."""
122
  if shutdown_event.is_set():