实现缓存的方式,有多种:本地内存缓存,数据库缓存,文件系统缓存。这里介绍使用Redis数据库进行缓存。
配置
1 CACHES ={ 2 "default": { 3 "BACKEND": "django_redis.cache.RedisCache", 4 "LOCATION": "redis://127.0.0.1:6379/1", 5 "OPTIONS": { 6 "CLIENT_CLASS": "django_redis.client.DefaultClient", 7 "PASSWORD": "mysecret",
8 "CONNECTION_POOL_KWARGS": {"max_connections": 100} # 连接池最大连接数
9 }}}
在settings.py配置完后执行python manage.py createcachetable
缓存有站点缓存,和单个view缓存
站点缓存:
1 MIDDLEWARE =[ 2 #站点缓存 , 注意必须在第一个位置 3 'django.middleware.cache.UpdateCacheMiddleware', 4 ... 5 #站点缓存, 注意必须在最后一个位置 6 'django.middleware.cache.FetchFromCacheMiddleware', 7 ]
视图缓存:
1 from django.shortcuts importrender 2 from django.views.decorators.cache importcache_page 4 from cache.models importFoo 6 #在需要缓存的视图上添加装饰器, 参数是设置timeout 超时时间, 单位是秒, 7 @cache_page(60) 8 defindex(request): 9 bar =Foo.objects.all() 10 return render(request, 'cache/index.html', {'bar': bar})