Django cache configuration Redis usage details

  • 2021-07-26 08:00:29
  • OfStack

1. Introduction to cache

Because Django is a dynamic website, all requests will go to the data for corresponding operations. When the program visits a large amount of time, the time consumption will inevitably become more obvious. The simplest solution is to use: cache.

Working principle of cache: Cache is to save some commonly used data in memory or memcache. When users access these data within a certain time, they will no longer perform database and rendering operations, but directly obtain data from memory or memcache cache, and then return it to users.

Django provides six caching methods:

Develop debug cache Memory cache File cache Database cache Memcache cache (using python-memcached module) Memcache cache (using pylibmc module)

There is not much introduction here. Those who are interested can go to the official document: https://docs.djangoproject.com/en/dev/topics/cache/

2. Redis cache

To configure the Redis cache on Django, you need to install the dependencies:


pip3 install django-redis

settings. py configuration:


CACHES = {
  "default": {
    "BACKEND": "django_redis.cache.RedisCache",
    "LOCATION": "redis://127.0.0.1:6379",
    "OPTIONS": {
      "CLIENT_CLASS": "django_redis.client.DefaultClient",
      "CONNECTION_POOL_KWARGS": {"max_connections": 100}
      # "PASSWORD": " Password ",
    }
  }
}

Connection in view (manual operation redis):


from django.shortcuts import HttpResponse
from django_redis import get_redis_connection

def index(request):
  r = get_redis_connection("default")
  r.hmset("name_a", {"key_a": "value_a", "key_b": "value_b"})
  return HttpResponse(" Settings redis")

def order(request):
  r = get_redis_connection("default")
  val = r.hmget("name_a", ["key_a", "key_b"])
  print(val) # [b'value_a', b'value_b']
  return HttpResponse(" Get redis")

3. Application

Whole station use cache

Using middleware, after a series of authentication operations, if the content exists in the cache, FetchFromCacheMiddleware is used to obtain the content and return it to the user. Before returning it to the user, it is judged whether it already exists in the cache. If it does not exist, UpdateCacheMiddleware will save the cache to the cache, thus realizing the whole station cache.


MIDDLEWARE = [
  'django.middleware.cache.UpdateCacheMiddleware', #  Put it in the first place 1
  #  Other middleware ...
  'django.middleware.cache.FetchFromCacheMiddleware', #  Put it at the end 
]

CACHE_MIDDLEWARE_ALIAS = ""     #  Cache alias for storage 
CACHE_MIDDLEWARE_SECONDS = 600    #  Number of seconds per page should be cached  
CACHE_MIDDLEWARE_KEY_PREFIX = ""   #  If you use the same Django To install a shared cache between multiple sites, set it to the site name or this Django Instance to prevent key conflicts. If you don't care, please use an empty string. 

Test


from django.shortcuts import HttpResponseimport time
def index(request):
  t = time.time()
  return HttpResponse(" Time: {}".format(str(t)))

def home(request):
  t = time.time()
  return HttpResponse(" Time: {}".format(str(t)))

It can be found that the time when index or home pages return for the first time is the same within 10 minutes.

Separate view caching (remember to cancel the middleware configuration of full-site caching)


from django.shortcuts import HttpResponse
from django.views.decorators.cache import cache_page
import time

@cache_page(60 * 10)
def index(request):
  t = time.time()
  return HttpResponse(" Time: {}".format(str(t)))

def home(request):
  t = time.time()
  return HttpResponse(" Time: {}".format(str(t)))

This time, the return time of the first visit to index page needs to change after 10 minutes of re-visit, while the return time of home page changes all the time.

Template local view uses


# 1. Introduce TemplateTag
  {% load cache %}

# 2. Using cache 
  {% cache 600 name %} #  Cache timeout ( Seconds )  And   The name of the cache fragment ( Use the name as is )
     Cache content 
  {% endcache %}

Example:


# views.py
from django.shortcuts import render
import time

def index(request):
  t = time.time()
  return render(request, "index.html", {"t": t})

# index.html
<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>

{% load cache %}

{% cache 10 current_time %}
  <h1>{{ t }}</h1>
{% endcache %}

</body>
</html>

4. Use scenario description


# 1 Generally speaking, we use  Django  To build 1 A website, to use the database, etc. 

from django.shortcuts import render
def index(request):
  #  Read database, etc   And rendered to a web page 
  #  The results obtained by the database are saved to the  queryset  Medium 
  return render(request, 'index.html', {'queryset':queryset})
#  You have to read the database every time you access it like this, 1 There is nothing wrong with a small website. When the traffic is very large,   There will be many database queries, which will definitely cause problems such as slow access speed and more server resources. 

#--------------------------------------------------------------------

from django.shortcuts import render
from django.views.decorators.cache import cache_page
 
@cache_page(60 * 10) #  Seconds, in this case, cache 10 Minutes, don't write directly 600 Is to improve readability 
def index(request):
  #  Read database, etc   And rendered to a web page 
  return render(request, 'index.html', {'queryset':queryset})
#  When using the cache After, the access situation becomes as follows: access 1 When the URL is ,  Try to start from  cache  Is there any in the search   Cache content, if the required data has no cache content in the cache, go to the database to get it, render and return to the page, and at the same time   Save this data in the cache, in the 1 Within a certain time, when the user visits the page again, there is no need to go to the database to retrieve it   Now, get the data directly from the cache. 

Related articles: