django缓存,适用于页面经常被访问,但页面数据不会经常改变的地方
- 数据库缓存settings配置
# 数据库缓存配置,然后python manage.py createcachetable生成缓存表
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
# 缓存表的名字
'LOCATION': 'my_cache_table'
}
}
- redis缓存settings配置
# redis做缓存
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://192.168.1.101:6379/2', # redis地址(无密码),后面表示使用第二个数据库
# 'LOCATION': 'redis://密码@192.168.1.101:6379/2', # redis地址(有密码),后面表示使用第二个数据库
}
}
views.py,使用装饰器缓存@cache_page(缓存时间(秒)),还有使用局部缓存
from django.views.decorators.cache import cache_page
# 缓存装饰器,后面为时间(秒)
@cache_page(1)
def index(request): # 格式时间
my_time1 = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
my_time2 = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
return render(request, 'index.html', locals())
HTML页面
<h1>装饰器缓存{{ my_time1 }}</h1>
局部缓存,要先加载缓存,2为缓存两秒,名字随意
{% load cache %}
{% cache 2 'my' %}
<h2>{{ my_time2 }}</h2>
{% endcache %}
手动设置缓存,第一次将数据库里的数据读出来,渲染到也买你并保存到缓存里,下次请求来的时候先在缓存里面查找数据,没有则到再到数据库查找
视图函数
# 手动设置缓存
def my_cache(request):
from django.core.cache import cache # 手动设置缓存,导入底层的缓存
# 首先在缓存表里查数据
my_data = cache.get('all_data')
# 缓存表里没有再到数据库里查并将数据放入缓存表里
if not my_data:
my_data = Data.objects.all()
# cache可以直接把查询结果序列化,保存到缓存表里
cache.set('all_data', my_data, 20) # cache.set(key, value, timeout(秒))
return render(request, 'cache.html', locals())
HTML页面渲染
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>T</title>
</head>
<body>
<h1>手动设置缓存</h1>
{% for data in my_data %}
<p>{{ data.text }}</p>
{% endfor %}
</body>
</html>