一般缓存用于不经常更新的页面,这样可以提高用户重复浏览的速率,不至于一次一次的加载。
局部缓存
{% load cache %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>页面缓存</title>
</head>
<body>
<h2> {{ current_time }} </h2>
{% cache 10 'pre' %} # 局内自定义缓存时间
<h2>{{ pre_time }}</h2>
{% endcache %}
</body>
</html>
@cache_page(20) # 局部缓存时间
def index(request):
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
pre_time = datetime.now() - timedelta(days=3)
pre_time = pre_time.strftime("%Y-%m-%d %H:%M:%S")
return render(request,'index.html',locals())
全局缓存
配置settings
MIDDLEWARE = [
'django.middleware.cache.UpdateCacheMiddleware',#必须是第一个中间件
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware', # 必须是最后一个中间件
]
CACHE_MIDDLEWARE_SECONDS = 20 #设置超时时间 20秒
全局缓存要慎用,尤其是有时刻更新的页面和正在调试的页面的情况下。
如何判断信息是否缓存
from django.core.cache import cache
def cache_data(request):
# 首先判断数据是否在缓存中,如果在直接获取
users = cache.get('all_users')
if not users: # 如果不在缓存,查询数据库,将信息写入缓存
users = User.objects.all()
# cache可以直接把查询结果序列化
cache.set('all_users',users)
return render(request,'index1.html',locals())