Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to set a cache key with a timeout in Django.
Django
cache.set('user_123', user_data, timeout=[1])
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using quotes around numbers for timeout
Setting timeout to None as a string
✗ Incorrect
The timeout value should be an integer representing seconds. Here, 300 means the cache expires after 5 minutes.
2fill in blank
mediumComplete the code to delete a cache key in Django.
Django
cache.[1]('user_123')
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using clear deletes all cache, not a single key
Using pop is not a cache method
✗ Incorrect
The delete method removes a specific key from the cache.
3fill in blank
hardFix the error in the code to invalidate cache after updating a model instance.
Django
def save(self, *args, **kwargs): super().save(*args, **kwargs) cache.[1](f'user_{self.id}')
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using clear removes all cache
Using set overwrites cache instead of invalidating
✗ Incorrect
After saving the model, we delete the cache key to invalidate stale data.
4fill in blank
hardFill both blanks to create a cache key and set it with a timeout.
Django
cache_key = f'user_[1]' cache.[2](cache_key, user_data, timeout=600)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using delete instead of set
Using pk when id is expected
✗ Incorrect
The cache key uses the user's id. The set method stores data with a timeout.
5fill in blank
hardFill all three blanks to check cache, set if missing, and return data.
Django
cache_key = f'user_[1]' data = cache.[2](cache_key) if data is None: data = get_user_data([3]) cache.set(cache_key, data, timeout=300) return data
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using set instead of get to retrieve data
Using pk instead of user_id in function call
✗ Incorrect
The cache key uses id. We try to get cached data. If missing, we fetch data using user_id and cache it.