Spaces:
Configuration error
Configuration error
Commit ·
ed44705
1
Parent(s): df0a2e0
Updated the code to limit the api requests
Browse files- model/api.py +20 -0
- requirements.txt +2 -1
model/api.py
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from fastapi import FastAPI, UploadFile, File
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
from fastapi.staticfiles import StaticFiles
|
|
@@ -28,3 +33,18 @@ async def predict_emotion(file: UploadFile = File(...)):
|
|
| 28 |
image = Image.open(io.BytesIO(contents)).convert("RGB")
|
| 29 |
emotion = predict(image)
|
| 30 |
return {"emotion": emotion}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from slowapi import Limiter
|
| 2 |
+
from slowapi.util import get_remote_address
|
| 3 |
+
from slowapi.errors import RateLimitExceeded
|
| 4 |
+
from slowapi.responses import JSONResponse
|
| 5 |
+
from starlette.requests import Request
|
| 6 |
from fastapi import FastAPI, UploadFile, File
|
| 7 |
from fastapi.middleware.cors import CORSMiddleware
|
| 8 |
from fastapi.staticfiles import StaticFiles
|
|
|
|
| 33 |
image = Image.open(io.BytesIO(contents)).convert("RGB")
|
| 34 |
emotion = predict(image)
|
| 35 |
return {"emotion": emotion}
|
| 36 |
+
|
| 37 |
+
limiter = Limiter(key_func=get_remote_address)
|
| 38 |
+
app.state.limiter = limiter
|
| 39 |
+
|
| 40 |
+
@app.exception_handler(RateLimitExceeded)
|
| 41 |
+
def rate_limit_handler(request: Request, exc: RateLimitExceeded):
|
| 42 |
+
return JSONResponse(
|
| 43 |
+
status_code=429,
|
| 44 |
+
content={"detail": "Too many requests, slow down 😅"}
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
@app.post("/api/predict")
|
| 48 |
+
@limiter.limit("5/minute")
|
| 49 |
+
async def predict_emotion(file: UploadFile = File(...)):
|
| 50 |
+
...
|
requirements.txt
CHANGED
|
@@ -8,4 +8,5 @@ tqdm
|
|
| 8 |
requests
|
| 9 |
fastapi
|
| 10 |
uvicorn
|
| 11 |
-
python-multipart
|
|
|
|
|
|
| 8 |
requests
|
| 9 |
fastapi
|
| 10 |
uvicorn
|
| 11 |
+
python-multipart
|
| 12 |
+
slowapi
|