- Django提供了不同级别的缓存粒度
可以缓存特定视图的输出;
可以仅仅缓存那些很难生产出来的部分 可以缓存整个网站 - 设置缓存
可将数据缓存在数据库,文件系统,和内存中
#setting.py
# 使用内存来进行缓存
CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 60,
}
}
#使用redis进行缓存
安装包:pip install django-redis-cache
CACHES = {
"default": {
"BACKEND": "redis_cache.cache.RedisCache",
"LOCATION": "localhost:6379",
'TIMEOUT': 60,
},
}
- 缓存单个视图
django.views.decorators.cache定义了cache_page装饰器,用于对视图的输出进行缓存
from django.views.decorators.cache import cache_page
@cache_page(60 * 15)
def index(request):
return HttpResponse('hello1')
#return HttpResponse('hello2')
- 缓存模板片段
{% load cache %}
缓存时间,和缓存片段名
{% cache 500 hello %}
hello1
<!--hello2-->
{% endcache %}