Django provides a low-level cache API that allows you to access the cache from your Python code. Instead of caching entire pages, you may want to cache only specific data that will be used to render the display.
The django.core.cache.cache.set(key, value, timeout_seconds) function allows you to store any Python object that can be pickled in the cache. The set() function accepts three arguments—key, value, and timeout_seconds. The key argument is a string used to reference the object. The value argument is the object to be cached. The timeout_seconds argument specifies the number of seconds to cache the object.
The following code stores a list of Blog objects in the cache for 25 seconds:
from django.core.cache import cache blogs = Blog.objects.all() cache.set('Blog_List', blogs, 25)
The django.core.cache.cache.get(key) function accesses the cache and returns the value of the entry in the cache. If the entry is not found, None is returned. For example, the following code accesses the Blog list stored in the cache using the preceding example:
blogs = cache.get('Blog_List')
By the Way
The get() function can also accept a second argument that specifies a value to be returned instead of None if no entry is found:
blogs = cache.get('Blog_List', [])
The django.core.cache.cache.getmany(key_list) function accesses the cache and returns the values of the multiple cache entries. The getmany() function accepts a list of keys as its only argument. It returns a dictionary containing the keys from the arguments and their corresponding values in the cache. If the entry is not found or is expired, it is not included in the dictionary.
For example, the following code returns a dictionary containing the Date and User entries in the cache:
from datetime import datetime from django.core.cache import cache Date = datetime.now() cache.set('User', request.User, 60) cache.set('Date', datetime.now(), 60) . . . cache.get_many(['User', 'Date'])
Did you Know?
The cache API is key-based, so you can store an object in one view function and retrieve it in another.
The django.core.cache.cache.delete(key) function deletes the entry specified by the key argument in the cache. The delete() function has no return value and does not raise an error if the key is not found in the cache. The following example deletes the Blog_List entry from the cache:
cache.delete('Blog_List')
Try It Yourself: Cache and Retrieve a Specific Object Using the Cache APIIn this section, you will use the low-level cache API to implement caching at the object level. You will modify the home_view() view function to store and retrieve a list of Person objects using the cache API:
Listing 23.1. The home_view() View Function in the iFriends/Home/views.py File
|