Bird
0
0

Identify the error in this custom throttle class:

medium📝 Debug Q14 of 15
Django - DRF Advanced Features
Identify the error in this custom throttle class:
from rest_framework.throttling import SimpleRateThrottle

class CustomThrottle(SimpleRateThrottle):
    scope = 'custom'

    def get_cache_key(self, request, view):
        return request.user.id

# settings.py
REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_RATES': {
        'custom': '5/minute'
    }
}
Aget_cache_key should return a string, but returns an integer
Bscope should be set to 'rate' instead of 'custom'
CDEFAULT_THROTTLE_RATES key 'custom' is missing a time unit
DCustomThrottle must inherit from UserRateThrottle, not SimpleRateThrottle
Step-by-Step Solution
Solution:
  1. Step 1: Check get_cache_key return type

    The method returns request.user.id, which is an integer, but cache keys must be strings.
  2. Step 2: Validate other parts

    Scope 'custom' matches the throttle rate key, and inheritance from SimpleRateThrottle is valid.
  3. Final Answer:

    get_cache_key should return a string, but returns an integer -> Option A
  4. Quick Check:

    Cache key must be string [OK]
Quick Trick: Cache keys must be strings, not integers [OK]
Common Mistakes:
MISTAKES
  • Returning non-string cache keys
  • Misnaming throttle scope
  • Confusing throttle class inheritance

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes