-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtopic27.py
More file actions
56 lines (48 loc) 路 1.54 KB
/
Copy pathtopic27.py
File metadata and controls
56 lines (48 loc) 路 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
"""
Rate Limiting in FastAPI-
. What is Rate Limiting?
. Using slowapi Library
. FastAPI integration
. Testing
. Interview Questions
"""
# pip install slowapi
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from requests import status_codes
from slowapi import Limiter
from slowapi.errors import RateLimitExceeded
from slowapi.util import get_remote_address
app = FastAPI()
# Limiter = Limiter(key_func = get_remote_address)
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
# Error Handle
@app.exception_handler(RateLimitExceeded)
def rate_limit_handler(request: Request, exc: RateLimitExceeded):
return JSONResponse(
status_code=429,
content={
"detail":"Too many requests"
}
)
# Rate Limiter API
@app.get("/data")
@limiter.limit("5/minutes")
async def get_data(request: Request):
return {
"message":"Success"
}
"""
# Output: spam se bacha sakte hai, Ratelimiter ka use krke
INFO: Application startup complete.
INFO: 127.0.0.1:59821 - "GET / HTTP/1.1" 404 Not Found
INFO: 127.0.0.1:59821 - "GET /docs HTTP/1.1" 200 OK
INFO: 127.0.0.1:59821 - "GET /openapi.json HTTP/1.1" 200 OK
INFO: 127.0.0.1:64600 - "GET /data HTTP/1.1" 200 OK
INFO: 127.0.0.1:64600 - "GET /data HTTP/1.1" 200 OK
INFO: 127.0.0.1:64600 - "GET /data HTTP/1.1" 200 OK
INFO: 127.0.0.1:64600 - "GET /data HTTP/1.1" 200 OK
INFO: 127.0.0.1:64600 - "GET /data HTTP/1.1" 200 OK
INFO: 127.0.0.1:64600 - "GET /data HTTP/1.1" 429 Too Many Requests
"""