在文件開頭導入下面代碼,而後在函數上方添加緩存的裝飾器前端
from django.views.decorators.cache import cache_page
@cache_page(30)
Django中提供了6種緩存方式:python
經常使用的緩存配置redis
Memcache緩存數據庫
首先要建立緩存表django
python manage.py createcachetable [table_name]
CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'cache_table', 'TIMEOUT': '60', 'OPTIONS': { 'MAX_ENTRIES': '300', }, 'KEY_PREFIX': 'rock', 'VERSION': '1', } }
redis緩存緩存
首先要安裝django-redisapp
pip install django-redis
CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } }
代碼實現示例:
from django.forms import model_to_dict from django.http import JsonResponse from django.core.cache import cache from app.models import Engineer def my_cache_test(req): # 看緩存有沒有數據 res = cache.get('data') if res:return JsonResponse(res) else: # 查數據 data = Engineer.objects.all() # 把對象轉成字典 # model_to_dict() c_data = []
for i in data: c_data.append(model_to_dict(i)) result = {'my_data':c_data} # 設置緩存 cache.set('data',result,30) # 返回數據給前端 return JsonResponse(result)