Brief understanding of django cache mode and configuration
- 2021-07-24 11:09:25
- OfStack
Preface
Since 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,
1. Overview of caching:
The cache saves a return value of an views to memory or memcache. When someone visits it again within 5 minutes, it will no longer perform the operation in view, but directly get it from memory or the previously cached content in Redis and return it.
2. Six caching methods are available in Django:
Development and debugging Memory Documents Database Memcache Cache (python-memcached Module) Memcache Cache (pylibmc Module)2.1 Configuration
Development and debugging
# This is for starting debugging, and no operation is actually done internally
# Configuration:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache', # Engine
'TIMEOUT': 300, # Cache timeout (default 300 , None Means never expires, 0 Indicates immediate expiration)
'OPTIONS':{
'MAX_ENTRIES': 300, # Maximum number of caches (default 300 )
'CULL_FREQUENCY': 3, # After the maximum number of caches is reached, the proportion of the number of caches is eliminated, that is: 1/CULL_FREQUENCY (Default 3 )
},
'KEY_PREFIX': '', # Cache key Prefix of (default null)
'VERSION': 1, # Cache key The version of the (default) 1 )
'KEY_FUNCTION' Function name # Generate key The default function will be generated as: "Prefix : Version :key ")
}
}
# Customize key
def default_key_func(key, key_prefix, version):
"""
Default function to generate keys.
Constructs the key used by all other methods. By default it prepends
the `key_prefix'. KEY_FUNCTION can be used to specify an alternate
function with custom key making behavior.
"""
return '%s:%s:%s' % (key_prefix, version, key)
def get_key_func(key_func):
"""
Function to decide which key function to use.
Defaults to ``default_key_func``.
"""
if key_func is not None:
if callable(key_func):
return key_func
else:
return import_string(key_func)
return default_key_func
Memory
# This cache saves the contents to variables in memory
# Configuration:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'unique-snowflake',
}
}
# Note: Other configurations are the same as the development and debugging version
Documents
# This cache saves the contents to a file
# Configuration:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
'LOCATION': '/var/tmp/django_cache',
}
}
# Note: Other configurations are the same as the development and debugging version
Database
# This cache saves the contents to the database
# Configuration:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'my_cache_table', # Database table
}
}
# Note: Execute the Create Table command python manage.py createcachetable
Memcache Cache (python-memcached Module)
# This cache uses the python-memcached Modular connection memcache
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': 'unix:/tmp/memcached.sock',
}
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': [
'172.19.26.240:11211',
'172.19.26.242:11211',
]
}
}
Memcache Cache (pylibmc Module)
# This cache uses the pylibmc Modular connection memcache
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
'LOCATION': '127.0.0.1:11211',
}
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
'LOCATION': '/tmp/memcached.sock',
}
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
'LOCATION': [
'172.19.26.240:11211',
'172.19.26.242:11211',
]
}
}
Redis Cache (Dependence: pip3 install django-redis)
from django_redis import get_redis_connection
conn = get_redis_connection("default")
2.2 Application
Whole station use
Using middleware, through 1 If the content exists in the cache, use the FetchFromCacheMiddleware Get the content and return it to the user. Before returning it to the user, judge whether it already exists in the cache. If it does not exist, then UpdateCacheMiddleware The cache is saved to the cache, thus realizing the whole station cache
MIDDLEWARE = [
'django.middleware.cache.UpdateCacheMiddleware',
# Other middleware ...
'django.middleware.cache.FetchFromCacheMiddleware',
]
CACHE_MIDDLEWARE_ALIAS = ""
CACHE_MIDDLEWARE_SECONDS = ""
CACHE_MIDDLEWARE_KEY_PREFIX = ""
Separate view cache
Mode 1 :
from django.views.decorators.cache import cache_page
@cache_page(60 * 15)
def my_view(request):
...
Mode 2 :
from django.views.decorators.cache import cache_page
urlpatterns = [
url(r'^foo/([0-9]{1,2})/$', cache_page(60 * 15)(my_view)),
]
Local view use
a. Introduce TemplateTag
{% load cache %}
b. Using cache
{% cache 5000 Cache key %}
Cache content
{% endcache %}