Using the low-level cache API

The low-level cache API allows you to store objects in the cache with any granularity. It is located at django.core.cache. You can import it like this:

from django.core.cache import cache

This uses the default cache. It's equivalent to caches['default']. Accessing a specific cache is also possible via its alias:

from django.core.cache import caches
my_cache = caches['alias']

Let's take a look at how the cache API works. Open the shell with the command python manage.py shell and execute the following code:

>>> from django.core.cache import cache
>>> cache.set('musician', 'Django Reinhardt', 20)

We access the default cache backend and use set(key, value, timeout) to store a key named 'musician' with a value that is the string 'Django Reinhardt' for 20 seconds. If we don't specify a timeout, Django uses the default timeout specified for the cache backend in the CACHES setting. Now, execute the following code:

>>> cache.get('musician')
'Django Reinhardt'

We retrieve the key from the cache. Wait for 20 seconds and execute the same code:

>>> cache.get('musician')

No value is returned this time. The 'musician' cache key expired and the get() method returns None because the key is not in the cache anymore.

Always avoid storing a None value in a cache key because you won't be able to distinguish between the actual value and a cache miss.

Let's cache a QuerySet with the following code:

>>> from courses.models import Subject
>>> subjects = Subject.objects.all()
>>> cache.set('all_subjects', subjects)

We perform a QuerySet on the Subject model and store the returned objects in the 'all_subjects' key. Let's retrieve the cached data:

>>> cache.get('all_subjects')
<QuerySet [<Subject: Mathematics>, <Subject: Music>, <Subject: Physics>, <Subject: Programming>]>

We are going to cache some queries in our views. Edit the views.py file of the courses application and add the following import:

from django.core.cache import cache

In the get() method of the CourseListView, replace the following line:

subjects = Subject.objects.annotate(
total_courses=Count('courses'))

Replace it with the following ones:

subjects = cache.get('all_subjects')
if not subjects:
subjects = Subject.objects.annotate(
total_courses=Count('courses'))
cache.set('all_subjects', subjects)

In this code, we try to get the all_students key from the cache using cache.get(). This returns None if the given key is not found. If no key is found (not cached yet or cached but timed out), we perform the query to retrieve all Subject objects and their number of courses, and we cache the result using cache.set().

Run the development server and open http://127.0.0.1:8000/ in your browser. When the view is executed, the cache key is not found and the QuerySet is executed. Open http://127.0.0.1:8000/admin/ in your browser and expand the Memcached statistics. You should see usage data for the cache similar to the following screen:

Take a look at Curr Items, which should be 1. This shows that there is one item currently stored in the cache. Get Hits shows how many get commands were successful and Get Misses shows the get requests for keys that are missing. The Miss Ratio is calculated using both of them.

Now, navigate back to http://127.0.0.1:8000/ using your browser and reload the page several times. If you take a look at the cache statistics now, you will see several more reads (Get Hits and Cmd Get will increase).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.204.201