----------------------------------------------------------------------------------------------
单页面缓存
# index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>你好,世界</h1>
当前时间是:{{ ctime }}
</body>
</html>
# urls.py
from app01 import views
urlpatterns = [
path('index/', views.index),
]
# settings.py
# 新增以下配置
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', #指定缓存使用的引擎
# 'LOCATION': '/var/tmp/django_cache', #指定缓存的路径
'LOCATION': r'D:\cache', #指定缓存的路径
'TIMEOUT':300, #缓存超时时间(默认为300秒,None表示永不过期)
'OPTIONS':{
'MAX_ENTRIES': 300, # 最大缓存记录的数量(默认300)
'CULL_FREQUENCY': 3, # 缓存到达最大个数之后,剔除缓存个数的比例,即:1/CULL_FREQUENCY(默认剔除1/3过期)
}
}
}
# views.py
from django.shortcuts import render
from django.views.decorators.cache import cache_page
# Create your views here.
@cache_page(5)
def index(request):
import time
ctime = time.time()
return render(request,'index.html',context={'ctime':ctime})
----------------------------------------------------------------------------------------------
局部缓存
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>你好,世界</h1>
当前时间是:{{ ctime }}
<hr>
这里使用局部缓存:
{% load cache %}
<!-- 3表示缓存时间 current_time表示局部缓存的名称 -->
{% cache 3 'current_time' %}
当前时间是:{{ ctime }}
{% endcache %}
</body>
</html>
----------------------------------------------------------------------------------------------
缓存整个站点,是最简单的缓存方法
在 MIDDLEWARE_CLASSES 中加入 “update” 和 “fetch” 中间件
MIDDLEWARE_CLASSES = (
‘django.middleware.cache.UpdateCacheMiddleware’, #第一,重写了process_response
'django.middleware.common.CommonMiddleware',
‘django.middleware.cache.FetchFromCacheMiddleware’, #最后,重写了process_requset
)
“update” 必须配置在第一个
“fetch” 必须配置在最后一个
CACHE_MIDDLEWARE_SECONDS=5 #5表示缓存的时间 单位秒
|