Consider this Django view code snippet using the default memory cache backend:
from django.core.cache import cache
def get_data():
cache.set('key', 'value', timeout=5)
return cache.get('key')What will get_data() return immediately after setting the cache?
from django.core.cache import cache def get_data(): cache.set('key', 'value', timeout=5) return cache.get('key')
Think about what happens when you set and get a key immediately in the same cache.
The memory cache stores the key-value pair immediately. So getting the key right after setting it returns the stored value.
Which of the following CACHES settings correctly configures Redis as the cache backend in Django?
Redis backend in Django usually uses django_redis.cache.RedisCache and a Redis URL.
Option D correctly uses the django_redis backend and a Redis URL with database 1. Other options mix backends and locations incorrectly.
Given this Django cache setting and code snippet:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
from django.core.cache import cache
cache.set('foo', 'bar')
cache.get('foo')Running this code raises a connection error. What is the most likely cause?
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
from django.core.cache import cache
cache.set('foo', 'bar')
cache.get('foo')Check if the Memcached service is active and reachable at the specified address.
The connection error usually means the Memcached server is not running or not reachable at the given IP and port.
Assume Redis cache backend is configured with a 1-second timeout. This code runs:
from django.core.cache import cache
cache.set('temp', 'data', timeout=1)
import time
time.sleep(2)
value = cache.get('temp')What is the value of value after this code runs?
from django.core.cache import cache cache.set('temp', 'data', timeout=1) import time time.sleep(2) value = cache.get('temp')
Think about what happens when you get a cache key after its timeout expires.
After the 1-second timeout, the key expires and is removed from Redis, so getting it returns None.
You have multiple Django app servers running behind a load balancer. You want a cache backend that all instances share to keep data consistent. Which cache backend is best suited?
Consider which cache backend supports sharing data across multiple machines.
Redis is a networked cache server accessible by all app instances, making it ideal for shared caching. Local memory and file caches are local to each instance. Dummy cache does not store data.