शुरू करेंमुफ़्त में शुरू करें

रेट लिमिटर लागू करना

आप एक sentiment analysis API बना रहे हैं जहाँ उपयोगकर्ता टेक्स्ट का sentiment विश्लेषण कर सकते हैं. दुरुपयोग रोकने के लिए, आपको rate limiting लागू करनी है जो प्रति API key प्रति मिनट केवल 5 requests की अनुमति दे. RateLimiter क्लास पहले से बनी हुई है और आपको उसके भीतर is_rate_limited method जोड़ना है, जो 1 मिनट की time window के अंदर की गई requests की संख्या जाँचता है.

datetime लाइब्रेरी से datetime और timedelta क्लासेज़ पहले से import की गई हैं.

यह अभ्यास पाठ्यक्रम का हिस्सा है

FastAPI के साथ प्रोडक्शन में AI डिप्लॉय करना

पाठ्यक्रम देखें

अभ्यास निर्देश

  • current time लें और एक मिनट पहले का timestamp निकालें.
  • request list को फ़िल्टर करें ताकि पिछले एक मिनट के अंदर वाले timestamps ही रहें.
  • जाँचें कि हाल की requests की संख्या limit से अधिक तो नहीं है.

इंटरैक्टिव व्यावहारिक अभ्यास

इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।

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
कोड संपादित करें और चलाएँ