1. Let’s look at what caching is:

Cache is a class of media that can read data faster. It also refers to other storage methods that can speed up data reading. Usually used to store temporary data, the usual medium is memory, which is fast to read. It is generally more expensive to extract data from a database multiple times than to read it from memory or hard disk at once. For medium and large sites, using caching to reduce the number of visits to the database is one of the keys to improving site performance.

2. Why cache is used:

With Django, when a request reaches a view, the view extracts data from the database into a template for dynamic rendering. The result is the web page the user sees. If the user pulls data from the database and renders it on every request, performance will be significantly reduced, not only will the server be stressed, but the client will not be able to get a response immediately. If the rendered result can be placed in a faster cache, check whether there is a corresponding resource in the cache every time there is a request. If there is, the response can be directly taken out of the cache to save the time of fetching data and rendering, which can not only greatly improve the system performance, but also improve user experience.

Let’s look at a practical example. Each time we visit the home page, the following view extracts the data list from the database and renders it into the template. Most of the time, our data doesn’t update that often, so the data list doesn’t change. It is a waste of time for users to re-read the same data from the database when they visit the home page several times in a certain period of time.

from django.shortcuts import render def index(request): Article_list = article.objects.all () return render(request, 'index.html', {'article_list': article_list})Copy the code

Using the Cache Cache can help us solve this problem. When the user first visits, we extract the list of data from the database and store it in a cache (usually in memory, depending on your Settings). When a user visits the home page within a certain amount of time (15 minutes in this case), Django checks to see if the cache is out of date, and if it is, it reads the data directly from the cache and renders the template.

The from the django. Shortcuts import render the from django. Views. Decorators. Cache import cache_page @ cache_page (60 * 15) # of seconds, Def index(request): Article_list = article.objects. all() return render(request, 'index.html', {'article_list': Article_list}) ** Note: Remember to do the necessary Settings before using the cache **Copy the code

3. Now that we have covered caching, here are the six caching methods and configurations

3.1 Development debug Cache (this mode is used for development debugging and does not require any action)

In the settings.py file

CACHES = {' default ': {' BACKEND' : 'django. Core. Cache. Backends. Dummy. DummyCache', # cache background use engines' TIMEOUT ': 'OPTIONS':{'MAX_ENTRIES': 300, 'CULL_FREQUENCY': 1/CULL_FREQUENCY (default 3)},}Copy the code
3.2 Memory cache (Storing cached contents in memory area)

In the settings.py file

CACHES = {' default ': {' BACKEND' : 'django. Core. Cache. Backends. Locmem. LocMemCache', # specify cache using engine 'LOCATION' : 'unique-snowflake', # unique value of variable written in memory 'TIMEOUT':300, # cache TIMEOUT (default :300 seconds,None means never expired) 'OPTIONS':{'MAX_ENTRIES': CULL_FREQUENCY: 1/CULL_FREQUENCY (default: 3)}}Copy the code
3.3 File Cache (Storing cached contents in the file area)

In the settings.py file

CACHES = {' default ': {' BACKEND' : 'django. Core. Cache. Backends. Filebased. FileBasedCache', # specify cache using engine 'LOCATION' : 'D:\test\cache', # specify cache path 'TIMEOUT':300, # Cache TIMEOUT (default :300 seconds,None means never expired) 'OPTIONS':{'MAX_ENTRIES': CULL_FREQUENCY: 1/CULL_FREQUENCY (default: 3)}}Copy the code
3.4 Database cache (Save the cache contents to the database area)

In the settings.py file

CACHES = {' default ': {' BACKEND' : 'django. Core. Cache. Backends. Db. DatabaseCache', # specify cache using engine 'LOCATION' : 'cache_table', # database table' OPTIONS':{'MAX_ENTRIES': 300, 'CULL_FREQUENCY': 1/CULL_FREQUENCY (default 3)}}Copy the code
3.5 Memcache (Using the Python-memcached module)

Memcached is Django’s natively supported caching system. To use Memcached, you need to download the Memcached support library, python-memcached, or the Pylibmc settings.py file

CACHES = {' default ': {' BACKEND' : 'django. Core. Cache. Backends. Memcached. MemcachedCache', # specify cache using engine 'LOCATION' : '192.168.10.100:8888', # specify Memcache server IP address and port 'OPTIONS':{'MAX_ENTRIES': 300, # Maximum number of cached records (default 300) 'CULL_FREQUENCY': 1/CULL_FREQUENCY (default 3)}}Copy the code

LOCATION can also be configured as follows:

'LOCATION': 'Unix :/ TMP /memcached. Sock ', # specify the host name in the local area network with the socket as Memcache 'LOCATION': [# 192.168.10.100:11211, '192.168.10.101:11211', '192.168.10.102:11211']Copy the code
3.6 Memcache (Using the PyliBMC Module)

In the settings.py file

CACHES = { 'default': { 'BACKEND': 'django. Core. Cache. Backends. Memcached. PyLibMCCache', # specify cache use engines' LOCATION ':' 192.168.10.100:11211 ', 'OPTIONS':{'MAX_ENTRIES': 300, 'CULL_FREQUENCY': 1/CULL_FREQUENCY (default 3)},}Copy the code

LOCATION can also be configured as follows:

'LOCATION': 'Unix :/ TMP /memcached. Sock ', # specify the host name in the local area network with the socket as Memcache 'LOCATION': [# 192.168.10.100:11211, '192.168.10.101:11211', '192.168.10.102:11211']Copy the code

4. Cache application area

4.1 Use of single Pages (with cache_page Decorator)

The cache view layer is configured in the configuration file to implement caching

The from the django. Views. Decorators. Cache import cache_page import time from the models import * # single page USES, @cache_page(15) def index(request): BookList = book.objects.all () return render(request,"index.html",locals())Copy the code
4.2 Global Usage (Implemented through middleware)

The user’s request passes through the middleware and goes through a series of authentication operations. If the requested content exists in the cache, FetchFromCacheMiddleware is used to obtain the content and return it to the user

Before returning it to the user, the UpdateCacheMiddleware determines if it already exists in the cache. If not, the UpdateCacheMiddleware saves the cache to Django’s cache for site-wide caching

The request comes in, from the top down to the middleware; When responding, go from bottom to top middleware. Therefore, get pages last and save pages first

MIDDLEWARE = [# put page, should be on the front 'django. MIDDLEWARE. Cache. UpdateCacheMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # take page in this position 'django. Middleware. Cache. FetchFromCacheMiddleware', # finallyCopy the code
4.3 Use of page layout
{{ctime}} {% endCache %} {{ctime}} {% endcache %}Copy the code

Above is xiaobian today for you to bring content

Xiaobian myself is a Python development engineer. I spent three days to organize a set of Python learning tutorials from the most basic Python scripts to Web development, crawlers, data analysis, data visualization, machine learning, etc. These materials can be obtained by clicking on the friends who want them