Spaces:
Paused
Paused
Download apps/api/src/app/rate_limit.py from nathycodes/presentercoach: direct link, hf CLI and curl.
- Browser
- Download file 857 Bytes
-
https://huggingface.co/spaces/nathycodes/presentercoach/resolve/main/apps/api/src/app/rate_limit.py
- Command line
-
hf download hf://spaces/nathycodes/presentercoach/apps/api/src/app/rate_limit.py
-
curl -L -o rate_limit.py https://huggingface.co/spaces/nathycodes/presentercoach/resolve/main/apps/api/src/app/rate_limit.py
857 Bytes
| import time | |
| from collections import defaultdict, deque | |
| from collections.abc import Callable | |
| from fastapi import HTTPException, Request, status | |
| WINDOW_SECONDS = 60 | |
| _hits: dict[str, deque[float]] = defaultdict(deque) | |
| def rate_limit(limit: int) -> Callable: | |
| def dependency(request: Request) -> None: | |
| client = request.client.host if request.client else "unknown" | |
| key = f"{client}:{request.url.path}" | |
| now = time.time() | |
| window_start = now - WINDOW_SECONDS | |
| bucket = _hits[key] | |
| while bucket and bucket[0] < window_start: | |
| bucket.popleft() | |
| if len(bucket) >= limit: | |
| raise HTTPException( | |
| status_code=status.HTTP_429_TOO_MANY_REQUESTS, | |
| detail="Rate limit exceeded. Try again shortly.", | |
| ) | |
| bucket.append(now) | |
| return dependency | |