一、配置
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://localhost:6380/0",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"PICKLE_VERSION": -1,
}
}
}
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
二、设置Model级别的缓存
def article(request):
aid = int(request.GET.get('aid', 1))
article = cache.get('article_%d'%aid)
if not article:
print('数据库的文章')
article = Article.objects.get(id=aid)
cache.set('article_%d'%aid,article)
comments = cache.get('comments_%d'%aid)
if not comments:
print('数据库的评论')
comments = Comment.objects.filter(aid=aid)
cache.set('comments_%d'%aid,comments)
return render(request, 'article.html', {'article': article, 'comments': comments})
三、设置页面级别的缓存
- helper.py 将装饰器写到单独的文件(未设置缓存时间)
from django.core.cache import cache
def page_cache(view_fun):
def handle_cache(request,*args,**kwargs):
key = 'PAGES_%s'%request.get_full_path()
response = cache.get(key)
if not response:
print('数据库数据')
response = view_fun(request,*args,**kwargs)
cache.set(key,response)
return response
return handle_cache
- 改写装饰器,添加缓存时间参数(装饰器嵌套,实现为装饰器添加参数)
def page_cache(n):
def handle_view(view_fun):
def handle_cache(request,*args,**kwargs):
key = 'PAGES_%s'%request.get_full_path()
response = cache.get(key)
if not response:
print('from views')
response = view_fun(request,*args,**kwargs)
cache.set(key,response,n)
else:
print('from cache')
return response
return handle_cache
return handle_view
from .helper import page_cache
@page_cache(n) #参数n为缓存时间,需要使用改造后的装饰器
def home(request):
...
return render(request, 'home.html')
@page_cache(n)
def article(request):
...
return render(request, 'article.html')