安装缓存后端
pip install django-redis-cache
配置django缓存为redis
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': '127.0.0.1:6379',
"OPTIONS": {
"CLIENT_CLASS": "redis_cache.client.DefaultClient",
},
'KEY_PREFIX':'kakaRedisTest',
'TIMEOUT':480,
},
}
配置url
from django.conf.urls import url
from django.contrib import admin
from blog.views import * #new
from django.views.decorators.cache import cache_page #new
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', index, name='index'),
url(r'^index2/$', cache_page(3)(Index2.as_view()), name='index2'),
]
视图函数
from django.shortcuts import render
from django.views.generic import TemplateView #new
from datetime import datetime #new
from django.core.cache import cache #new
#from django.views.decorators.cache import cache_page
# Create your views here.
def index(request):
dt = datetime.now().second
key = 'titles'
titles_cached = cache.get(key)
if not titles_cached:
titles = [(dt, 'kylie'), (dt,'coco'), (dt, 'camel')]
cache.set(key,titles)
else:
titles = titles_cached
context = {'dt':dt, 'titles':titles}
return render(request, 'index.html', context)
class Index2(TemplateView):
template_name = 'index2.html'
def get_context_data(self, **kwargs):
dt = datetime.now().second
return {'dt': dt}
模板index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% load cache %}
{% cache 3 titleCache %}
<h1>cached seconds:{{ dt }}</h1>
{% endcache %}
<h1>seconds:{{ dt }}</h1>
<ul>
{% for title in titles %}
<li>{{ title.0}},{{ title.1 }}</li>
{% endfor %}
</ul>
</body>
</html>
index2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>seconds:{{ dt }}</h1>
</body>
</html>