Aan de slagGa gratis aan de slag

Implementing rate limiter

You're building a sentiment analysis API where users can analyze texts for sentiments. To prevent abuse, you need to implement rate limiting that allows only 5 requests per minute per API key. The RateLimiter class is already created and you have to add the is_rate_limited method within the RateLimiter class that checks the number of requests that have been made within the 1 minute time window.

The datetime and timedelta classes from the datetime library have been pre-imported.

Deze oefening maakt deel uit van de cursus

Deploying AI into Production with FastAPI

Cursus bekijken

Oefeninstructies

  • Get the current time and calculate the timestamp for one minute ago.
  • Filter the request list to keep only timestamps within the last minute.
  • Check if the number of recent requests exceeds the limit.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

def is_rate_limited(self, api_key: str) -> bool:
    # Get current time and the timestamp for one minute ago
    now = _____
    minute_ago = now - _____(minutes=1)
    
    # Remove requests older than 1 minute
    self.requests[api_key] = [
        req_time for req_time in self.requests[api_key]
        if req_time > _____]
    
    # Check if no. of requests exceeded the set limit
    if len(self.requests[api_key]) ____ self.requests_per_minute:
        return True
    self.requests[api_key].append(now)
    return False
Code bewerken en uitvoeren