Previous Page Next Page

Implementing a Per-Object Cache

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 API

In 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:

1.
Open the iFriends/Home/views.py file in an editor.

2.
Add the following import statement to import the cache package:

from django.core.cache import cache

3.
Add the following line of code, shown in Listing 23.1, to determine if the List of Person objects is already cached:

pList = cache.get('PersonList')

4.
Add the following lines of code, shown in Listing 23.1, to get a list of Person objects and store it in the cache if it isn't already there:

if pList == None:
    pList = Person.objects.all()
    cache.set('PersonList', pList, 600)

5.
Modify the following line of code, shown in Listing 23.1, to set the pList entry in the rDict dictionary to the value returned from the cache:

rDict['pList'] = pList

6.
Save the iFriends/Home/views.py file.

Listing 23.1. The home_view() View Function in the iFriends/Home/views.py File

def home_view(request):
    rDict = {}
    pList = cache.get('PersonList')
    if pList == None:
        pList = Person.objects.all()
        cache.set('PersonList', pList, 600)
    rDict['pList'] = pList
    rDict['announceList'] = Announcement.on_site.all()

    currentSite = Site.objects.get_current()
    if (currentSite.domain == 'iFriends.test'):
        hpTemplate = 'home/homepage.html'
        rDict['quotes'] = Quote.objects.all()
    elif (currentSite.domain == 'iNews.test'):
        hpTemplate = 'home/newshomepage.html'
        rDict['storyList'] = Story.on_site.all()

    return render_to_response(hpTemplate, rDict,
                              context_instance = RequestContext(request))


Previous Page Next Page