Skip to content

Commit

Permalink
rate limit logging
Browse files Browse the repository at this point in the history
  • Loading branch information
russbiggs committed Dec 13, 2024
1 parent b5900a2 commit 254a0fd
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 8 deletions.
8 changes: 4 additions & 4 deletions openaq_api/openaq_api/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,7 @@ async def check_api_key(
limit = 60
limited = False
# check if its limited
now = datetime.now()
# Using a sliding window rate limiting algorithm
# we add the current time to the minute to the api key and use that as our check
key = f"{api_key}:{now.year}{now.month}{now.day}{now.hour}{now.minute}"
key = f"{api_key}"
# if the that key is in our redis db it will return the number of requests
# that key has made during the current minute
value = await redis.get(key)
Expand Down Expand Up @@ -121,6 +118,9 @@ async def check_api_key(
limited = True
requests_used = int(value)
ttl = await redis.ttl(key)
request.state.rate_limiter = (
f"{key}/{limit}/{requests_used}/{limit - requests_used}/{ttl}"
)

response.headers["x-ratelimit-limit"] = str(limit)
response.headers["x-ratelimit-remaining"] = str(requests_used)
Expand Down
6 changes: 2 additions & 4 deletions openaq_api/openaq_api/middleware.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import logging
import time
from os import environ
from fastapi import Response
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.types import ASGIApp

Expand All @@ -14,6 +11,7 @@

logger = logging.getLogger("middleware")


class CacheControlMiddleware(BaseHTTPMiddleware):
"""MiddleWare to add CacheControl in response headers."""

Expand Down

0 comments on commit 254a0fd

Please sign in to comment.