Previous Page Next Page

Implementing a Per-Site Cache

After you have configured a caching backend, you can implement caching on the website. The easiest way to implement caching is at the site level. Django provides the django.middleware.cache.CacheMiddleware middleware framework to cache the entire site. Add the following entry to the MIDDLEWARE_CLASSES setting in the settings.py file to enable caching for the entire website:

' django.middleware.cache.CacheMiddleware',

Watch Out!

The CacheMiddleware application does not cache pages that have GET or POST. When you design your website, make certain that pages that need to be cached do not require URLs that contain query strings.


After you enable the CacheMiddleware framework, you need to add the following required settings to the settings.py file:

By the Way

You can enable the same cache for multiple sites that reside on the same Django installation. Just add the middleware to the settings.py file for each site.


The CacheMiddleware framework also allows you to restrict caching to requests made by anonymous users. If you set CACHE_MIDDLEWARE_ANONYMOUS_ONLY in the settings.py file to True, requests that come from logged-in users are not cached.

Watch Out!

If you use the CACHE_MIDDLEWARE_ANONYMOUS_ONLY option, make certain that AuthenticationMiddleware is enabled and is listed earlier in the MIDDLEWARE_CLASSES setting.


Did you Know?

The CacheMiddleware framework automatically sets the value of some headers in each HttpResponse. The Last-Modified header is set to the current date and time when a fresh version of the page is requested. The Expires header is set to the current date and time plus the value defined in CACHE_MIDDLEWARE_SECONDS. The Cache-Control header is set to the value defined in CACHE_MIDDLEWARE_SECONDS.


Try It Yourself: Implement Caching at the Site Level

In this section, you will use the CacheMiddleware framework to implement caching at the site level. Follow these steps to enable and configure the CacheMiddleware framework:

1.
Stop the development server.

2.
Open the iFriends/settings.py file in an editor.

3.
Add the following line to the MIDDLEWARE_CLASSES setting:

' django.middleware.cache.CacheMiddleware',

4.
Add the following setting to the file to configure the CacheMiddleware framework to cache data for 2 minutes:

CACHE_MIDDLEWARE_SECONDS = 120

5.
Add the following setting to the file to configure the CacheMiddleware framework and to add the iFriends prefix to items cached on this site:

CACHE_MIDDLEWARE_KEY_PREFIX = 'iFriends'

6.
Save the iFriends/settings.py file.

7.
Start the development server.


Previous Page Next Page