緩存(cache),其做用是緩和較慢存儲的高頻次請求,簡單來講,就是加速滿存儲的訪問效率。python
# 內存緩存:local-memory caching CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } } # 文件系統緩存:filessystem caching CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': '/var/tem/django_cache', } }
這是Django推薦的緩存系統,也是分佈式內存對象緩存系統(注意,它的分佈式邏輯在客戶端)。Django內置支持,集成度比較好。redis
安裝:django
pip install python-memcached
配置settings.py緩存
CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': [ '127.0.0.1:8000', ] } } # 在MIDDLEWARE中加上, MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', ... 'django.middleware.cache.FetchFromCacheMiddleware', ]
在views.pyless
# 方法1: from django.views.decorators.cache import cache_page # 首頁 60*15表示緩存15分鐘 @cache_page(60*15) def index(request): pass # 方法2:直接在路由urls.py中實現 from django.views.decorators.cache import cache_page urlpatterns = [ path('index/', cache_page(60*15)(views.index)), ]
若是隻想緩存某個字段的話分佈式
from django.core.cache import cache def test(request): key = '我是緩存值' time= 60 result= cache.get(key) if not result: result = '' cache.set(key, result, time) return result
# 安裝包 pip install django-redis==4.9.0 pip install hiredis==0.2.0
同時安裝了hiredis,其做用是提高Redis解析性能。ide
在settings.py配置緩存memcached
REDIS_URL = '127.0.0.1:6379:1' CCACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': REDIS_URL, 'TIMEOUT': '300', 'OPTIONS': { # 'PASSWORD': '對應的密碼', 'CLIENT_CLASS': 'django_redis.client.DefaultClient', 'PARSER_CLASS': 'redis.connection.HiredisParser', }, 'CONNECTION_POOL_CLASS': 'redis.connection.BlockingConnectionPool', } }
# 直接在settings.py的MIDDLEWARE中的第一行增長 'django.middleware.cache.UpdateCacheMiddleware', # 但通常不這麼用
緩存url函數
函數緩存的用法,只須要增長裝飾器便可。好比:Model層的Post.hot_posts的更新頻率不高,那麼能夠進行比較長的緩存。post
from django.core.cache import cache class Post(models.Model): @classmethod def hot_posts(self): result = cache.get('hot_posts') if not result: result = cls.objects.filter(status=cls.STATUS_NORMAL).order_by('-pv') cache.set('hot_posts', result, 10*60) return result
若是須要緩存部分的模板數據時。能夠這麼作,好比緩存50s。
{% load cache %}
{% cache 50 sidebar %}
...sidebar...
{% endcache %}
此時只須要把要緩存的內容用cache標籤抱起來便可。