安裝包:pip install django-redis-cache
CACHES = {
"default": {
"BACKEND": "redis_cache.cache.RedisCache",
"LOCATION": "localhost:6379",
'TIMEOUT': 60,
},
}
參數TIMEOUT:緩存的默認過期時間,以秒爲單位,這個參數默認是300秒,即5分鐘;設置TIMEOUT爲None表示永遠不會過期,值設置成0造成緩存立即失效
redis常用操作命令:
鏈接:redis-cli
切換數據庫:select 1
查看鍵:keys *
查看值:get 鍵
可以使用裝飾器來對視圖函數輸出進行緩存:
from django.views.decorators.cache import cache_page
@cache_page(60 * 15) # 默認爲秒
def index(request):
模板片段緩存:
{% load cache %}
{% cache 500 code_name %} {# timeout設置及代碼片段命名 #}
''' {# code_block #}
{% endcache %}
底層緩存API:
from django.core.cache import cache
設置:cache.set(鍵,值,有效時間)
獲取:cache.get(鍵)
刪除:cache.delete(鍵)
清空:cache.clear()