环境
redis
django-redis
配置
settings.py
CACHES={“default”:{“BACKEND”:”django_redis.cache.RedisCache”,”LOCATION”:”redis://127.0.0.1:6379/1″,”OPTIONS”:{“CLIENT_CLASS”:”django_redis.client.DefaultClient”,”PASSWORD”:”mysecret”
}
}
}
pythonmanage.pycreatecachetable1
缓存有站点缓存,和单个view缓存
站点缓存:
settings.py
MIDDLEWARE=[#站点缓存,注意必须在第一个位置
‘django.middleware.cache.UpdateCacheMiddleware’,
…#站点缓存,注意必须在最后一个位置
‘django.middleware.cache.FetchFromCacheMiddleware’,
]
视图缓存:
views.py
fromdjango.shortcutsimportrenderfromdjango.views.decorators.cacheimportcache_pagefromcache.modelsimportFoo#在需要缓存的视图上添加装饰器,参数是设置timeout超时时间,单位是秒,@cache_page(60)defindex(request):
bar=Foo.objects.all()returnrender(request,’cache/index.html’,{‘bar’:bar})