在Django中,用户的请求到达视图时,视图会从数据库中获取数据,然后放到前端模板中进行动态渲染,渲染之后就能是⽤户看到的网页。
但是如果用户每次请求时,视图都从数据库提取数据并渲染,将会极大降低性能,提升服务器压力,客户端也因此无法及时获得响应。
此时可以使用缓存技术,将渲染后的结果放到缓存中,之后每次获得请求时,首先检查缓存中是否存在对应数据,如果存在就直接从缓存中获取数据并返回响应,这样可以大大节省从数据库中读取数据和页面渲染的时间。
缓存主要适用于对实时性能要求不高的页面。因此存放在缓存的通常是频繁访问且不经常进行修改的数据。
在Django中缓存的实现方式主要有:数据库缓存、文件缓存、 redis缓存等。

settings.py文件添加配置

实际项目中选择一种缓存方式进行配置即可。

  1. 数据库缓存
CACHES = {
    'default': {
    	# 指定缓存使⽤的引擎
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'my_cache_table',
    }
}

然后生成缓存表

python manage.py createcachetable
  1. 文件缓存
CACHES = {
    'default': {
    	# 指定缓存使⽤的引擎
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 
        # 指定缓存的路径
        'LOCATION': '/var/tmp/django_cache', 
        # 缓存超时时间
        'TIMEOUT':300,
        'OPTIONS':{
        	# 最⼤缓存记录的数量
            'MAX_ENTRIES': 300, 
            'CULL_FREQUENCY': 3, 
        }
    }
}
  1. redis缓存
CACHES = {
    'default': {
    	# 指定缓存使⽤的引擎为redis
        'BACKEND': 'django_redis.cache.RedisCache',
		# 缓存地址,有密码
        # 'LOCATION':'redis://:123456@127.0.0.1:6379/1',
		# 缓存地址,无密码
        'LOCATION': 'redis://127.0.0.1:6379/1',
    }
    }
  1. 全站缓存额外配置
MIDDLEWARE = [
	# 必须添加在开头
    'django.middleware.cache.UpdateCacheMiddleware',
    ...
    # 必须添加在结尾
    'django.middleware.cache.FetchFromCacheMiddleware',
]
# 设置超时时间
CACHE_MIDDLEWARE_SECONDS = 20

路由配置

app_name = 'App01'
urlpatterns = [
	# 使用全局缓存
	path('index/', views.index, name='index'),
	# 使用部分缓存
    path('partial/', views.cache_partial, name='partial'),
    # 使用自定义缓存
    path('custom/', views.cache_custom, name='custom'),
]

视图函数使用

# 设置缓存过期时间
@cache_page(30)
def index(request):
    current = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print(current)
    # 使用当前时间和前端页面显示的时间进行对比来验证缓存设置是否成功
    return render(request, 'index.html', locals())


def cache_partial(request):
	# 页面一部分使用缓存处理,另一部分不使用
    current1 = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    current2 = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    return render(request, 'loaclcache.html', locals())


def cache_custom(request):
	# 获取缓存
    html = cache.get('index')
    if html:
        print('使用cache')
        return HttpResponse(html)
    else:
        print('未使用cache')
        current = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        html = loader.get_template('index.html').render({'current': current})
        # 设置缓存
        cache.set('index', html)
        print(html)
    return HttpResponse(html)

前端页面

index.html

<body>
<h1>{{ current }}</h1>
</body>

loaclcache.html

<body>
<p>
    {{ current1 }}
</p>
<hr>
<p>
    局部缓存: <br>
    {% cache 10 'current2' %}
        {{ current2 }}
    {% endcache %}
</p>
</body>

结果展示

  1. 查看设置了全局缓存的首页
  2. django redis 容器 django使用redis缓存_django redis 容器

  3. 刷新页面之后仍然显示同一个时间,说明设置成功。
  4. 局部缓存页面
  5. django redis 容器 django使用redis缓存_django_02


  6. django redis 容器 django使用redis缓存_django redis 容器_03

  7. 可以看到,页面的上部分未设置缓存,刷新页面后时间更新。而下部分设置了缓存,刷新页面后时间未改变。
  8. 自定义缓存页面
  9. django redis 容器 django使用redis缓存_python_04

控制台中打印了输出

未使用cache

再次刷新页面,控制台输出变为:

使用cache

前端页面仍然是

django redis 容器 django使用redis缓存_html_05


说明自定义缓存设置成功。