# 缓存是一类可以更快读取数据的介质统称,也指其他可以加快数据读取的存储方式
# 缓存使用场景: 主要适用于对页面实时性要求不高的页面,存放在缓存的数据,通常是频繁访问的,而不会经常修改数据
# 缓存方式: 数据库, 文件, 内存, redis等
1. 缓存配置
1.1 数据库缓存配置
# settings.py
CACHES = {
'default':{
'BACKEND':'django.core.cache.backends.db.DatabaseCache',
'LOCATION':'my_cache_table',
}
}
# 生成缓存表(终端执行)(my_cache_table)
python manage.py createcachetable
1.2 Redis缓存配置
# 1. 安装django-redis第三方库
pip install django-redis
# 2. settings.py配置
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache', # 指定缓存类型: redis缓存
'LOCATION': 'redis://:123@127.0.0.1:6379/1', #缓存地址,@前面是redis密码
# 'LOCATION':'redis://127.0.0.1:6379/1', #没密码
}
}
2. 缓存使用
2.1 视图缓存
# urls.py
path('',views.index,name="index"),
from django.views.decorators.cache import cache_page
@cache_page(20) # 缓存20秒
def index(request):
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
return render(request, 'index.html', locals()) # 缓存期间将不在向后端发起请求
#index.html
<body>
<h2>{{ current_time }}</h2>
</body>
2.2 模板局部缓存
# views.py
def index(request):
pre_time = datetime.now() - timedelta(days=3)
pre_time =pre_time.strftime('%Y-%m-%d %H:%M:%S')
print(pre_time)
return render(request, 'index.html', locals()) # 缓存期间将不在向后端发起请求
#index.html
{% load cache %} {# 导入后可以使用局部缓存 #}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>页面缓存</title>
</head>
<body>
{# 页面局部缓存 10:秒; 'pre':随便起 #}
{% cache 10 'pre' %}
<h2>{{ pre_time }}</h2>
{% endcache %}
</body>
</html>
2.3 全站缓存
# settings.py配置
MIDDLEWARE = [
'django.middleware.cache.UpdateCacheMiddleware', # 必须是第一个中间件
.....
.....
'django.middleware.cache.FetchFromCacheMiddleware', # 必须是最后一个中间件
]
CACHE_MIDDLEWARE_SECONDS = 20 # 设置超时时间 20秒
# urls.py
path('all/',views.cache_all,name="all"),
def cache_all(request):
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
return HttpResponse(current_time)
2.4手动设置缓存
# 设置缓存
cache.set(key,value,timeout)
# 获取缓存
cache.get(key)
#urls.py
path('cachedata/',views.cache_data,name="cache_data"),
# views.py
def cache_data(request):
# 1. 首先判断数据是否在缓存中,如果在直接获取
users = cache.get("all_users")
# 2. 如果不在缓存,查询数据库,将结果写入缓存
if not users:
users = User.objects.all()
# cache可以直接吧查询结果序列化
cache.set('all_users', users)
print(users)
return render(request, 'index1.html', locals())
<body>
<table border="1" width="80%">
{% for user in users %}
<tr>
<td>{{ user.username }}</td>
<td>{{ user.password }}</td>
</tr>
{% endfor %}
</table>
</body>