Bird
0
0

Consider this Django view code:

medium📝 Predict Output Q4 of 15
Django - Caching
Consider this Django view code:
from django.core.cache import cache

def sample_view(request):
    message = cache.get('greeting')
    if message is None:
        message = 'Welcome!'
        cache.set('greeting', message, timeout=60)
    return message

What will this view return on the first request when the cache is empty?
ANone, because the cache key does not exist yet
B'Welcome!' and cache stores this value for 60 seconds
CAn error, since cache.get returns None and is not handled
D'greeting' string literal
Step-by-Step Solution
Solution:
  1. Step 1: Check cache retrieval

    cache.get('greeting') returns None if key missing.
  2. Step 2: Handle missing cache

    Since message is None, it is set to 'Welcome!' and cached for 60 seconds.
  3. Final Answer:

    'Welcome!' and cache stores this value for 60 seconds -> Option B
  4. Quick Check:

    Is the cache key missing initially? Yes, so default is set [OK]
Quick Trick: If cache miss, set and return default value [OK]
Common Mistakes:
MISTAKES
  • Assuming cache.get returns an error on missing key
  • Expecting None to be returned without fallback
  • Confusing the cache key with its value

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes