实现缓存的方式,有多种,本地内存缓存,数据库缓存,文件系统缓存。这里介绍使用Redis数据库进行缓存。
环境
配置
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"PASSWORD": "mysecret"
}
}
}
python manage.py createcachetable
缓存有站点缓存,和单个view缓存
MIDDLEWARE = [
'django.middleware.cache.UpdateCacheMiddleware',
...
'django.middleware.cache.FetchFromCacheMiddleware',
]
from django.shortcuts import render
from django.views.decorators.cache import cache_page
from cache.models import Foo
@cache_page(60)
def index(request):
bar = Foo.objects.all()
return render(request, 'cache/index.html', {'bar': bar})