1.视图函数使用
配置:这里配置文件缓存,新建一个cache文件夹:
settings.py:
CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': os.path.join(BASE_DIR, 'cache') } }
views.py:
from django.views.decorators.cache import cache_page @cache_page(10) def cache(request): import time ctime = time.time() return render(request, 'cache.html', {'ctime': ctime})
urls.py:
url(r'^cache/$', views.cache),
cache.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>{{ ctime }}</h1> </body> </html>
每次访问/cache/在cache文件夹中会产生缓存文件,10秒后页面内容更新
2.局部视图使用(这里是Django框架最出色的方面之一):
{% load cache %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>{{ ctime }}</h1> {% cache 10 c1 %} <h1>{{ ctime }}</h1> {% endcache %} </body> </html>
这个页面可以做到,第一行的时间时刻在变,第二行每隔十秒变
3.全局缓存:
Django已经写好,只需要在settings.py中配置
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', ]
第一次请求过来,返回的时候存入缓存,第二次请求过来,直接从缓存中取。