開始使用免費開始

實作速率限制器

你正在建立一個情感分析 API,使用者可以分析文字的情緒。為了防止濫用,你需要實作速率限制:每個 API key 每分鐘只允許 5 次請求。RateLimiter 類別已建立,你必須在 RateLimiter 類別中加入 is_rate_limited 方法,用來檢查在 1 分鐘時間窗內已發出的請求次數。

datetime 函式庫中的 datetimetimedelta 類別已預先匯入。

本練習屬於課程

使用 FastAPI 將 AI 佈署到生產環境

檢視課程

練習說明

  • 取得目前時間,並計算 1 分鐘前的時間戳。
  • 篩選請求清單,只保留最近 1 分鐘內的時間戳。
  • 檢查近期請求數是否超過限制。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

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
編輯並執行程式碼