I. Introduction to cache
As Django is a dynamic website, all each request will go to the data for the corresponding operation, when the program access to a large number of time-consuming will inevitably be more obvious, the simplest way to solve the problem is to use: caching.
Caching principle: Cache is to save some commonly used data in memory or memcache, in a certain period of time when the user to access these data, it will no longer perform database and rendering and other operations, but directly from the memory or memcache cache to get the data, and then return to the user.
Django provides 6 caching methods:
- Development Debugging Cache
- memory cache
- file caching
- Database caching
- Memcache caching (using the python-memcached module)
- Memcache caching (using the pylibmc module)
There's not much to say here, so check out the official documentation if you're interested:/en/dev/topics/cache/
II. Redis Cache
To configure Redis caching in Django, you need to install the dependencies first:
pip3 install django-redis
Configuration:
CACHES = { "default": { "BACKEND": "django_redis.", "LOCATION": "redis://127.0.0.1:6379", "OPTIONS": { "CLIENT_CLASS": "django_redis.", "CONNECTION_POOL_KWARGS": {"max_connections": 100} # "PASSWORD": "Password". } } }
view to connect (manually manipulating redis):
from import HttpResponse from django_redis import get_redis_connection def index(request): r = get_redis_connection("default") ("name_a", {"key_a": "value_a", "key_b": "value_b"}) return HttpResponse("Setting up redis") def order(request): r = get_redis_connection("default") val = ("name_a", ["key_a", "key_b"]) print(val) # [b'value_a', b'value_b'] return HttpResponse("Get redis")
III. Applications
Site-wide use of caching
Using middleware, after a series of authentication and other operations, if the content exists in the cache, use FetchFromCacheMiddleware to get the content and return it to the user, and when returning it to the user before determining whether it already exists in the cache, and if it does not exist then UpdateCacheMiddleware will save the cache to the cache, thus realizing the Cache.
MIDDLEWARE = [ '', # Put it first # Other middleware... '', # At the end ] CACHE_MIDDLEWARE_ALIAS = "" # Cache aliases for storage CACHE_MIDDLEWARE_SECONDS = 600 # of seconds each page should be cached CACHE_MIDDLEWARE_KEY_PREFIX = "" # If you use the sameDjangoInstallation of shared caching between multiple sites,Please set it to the site name or thisDjangoOther strings specific to the instance,to prevent key conflicts。If you don't care.,Please use an empty string。
beta (software)
from import HttpResponseimport time def index(request): t = () return HttpResponse("timing:{}".format(str(t))) def home(request): t = () return HttpResponse("timing:{}".format(str(t)))
It can be noticed that the time of the first return of the index or home page is what it is, and the time is the same for up to 10 minutes thereafter.
Individual view caching (remember to uncheck the site-wide cache middleware configuration)
from import HttpResponse from import cache_page import time @cache_page(60 * 10) def index(request): t = () return HttpResponse("timing:{}".format(str(t))) def home(request): t = () return HttpResponse("timing:{}".format(str(t)))
This time, the time returned by the index page on the first visit takes 10 minutes to change on a second visit, while the time returned by the home page changes from time to time.
Template Local View Usage
# 1. Introducing TemplateTag {% load cache %} # 2. Using caching {% cache 600 name %} # Cache timeout (in seconds) and name of cache fragment (name used as is) Cached content {% endcache %}
Example:
# from import render import time def index(request): t = () return render(request, "", {"t": t})
# <!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>
IV. Description of use scenarios
# Generally we use Django to build a website with databases and such. from import render def index(request): # Reading databases and such and rendering them to web pages # # Database fetch results saved to queryset return render(request, '', {'queryset':queryset}) # Like this every visit to read the database, the general small site is not a problem, when the number of visits is very large, there will be many times the database query, will certainly cause access to slow down, the server resources occupied more problems. #-------------------------------------------------------------------- from import render from import cache_page @cache_page(60 * 10) # seconds, in this case caching for 10 minutes, not directly writing 600 is to improve readability def index(request): # Reading databases and such and rendering them to web pages # return render(request, '', {'queryset':queryset}) # When using thecacheempress,The visit becomes as follows:When visiting a Web site, Trying to get the best out of cache Find out if there's any Cached content,如果需要的数据在缓存中没有Cached content,Then go to the database and fetch,Render the return page,at the same time Save this data in the cache,over time,When the user revisits the page,There's no need to fetch it from the database. (modal particle intensifying preceding clause),Get the data directly from the cache。
This is the whole content of this article.