[toc]python
在FBV 或 CBV 须要缓存数据,又或者要进行全站缓存(利用中间件),单视图缓存(利用装饰器@cache_page(60 * 5) ),或者在template中使用{% cache 5 content_detail %} xxx {% endcache %} 进行页面局部缓存。这些场景都是须要用到缓存,来提升咱们响应用户请求速度的。在django框架中,给咱们提供了Cache组件,并暴露出知足以上4中需求的接口,咱们只须要配置好咱们的缓存引擎源及相关配置,就能够方便使用了。redis
博文图片挂了临时解决办法 django
given a URL, try finding that page in the cache if the page is in the cache: return the cached page else: generate the page save the generated page in the cache (for next time) return the generated page
在配置settings.py中CACHES = {} 字典中, 添加缓存源,key为缓存源的别名,django默认给咱们提供了一个默认缓存,而且是LocMemCahce即memcahe做为缓存引擎。固然能够配置多个缓存源,可是'default'只有一个,这个是默认使用的。固然默认的也能够替换,好比如今流行用reids做为默认缓存。api
查看官网: cache配置参数说明, hint 这里!缓存
CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake' } }
该缓存引擎,对每个进程是一个缓存,因此该缓存时线程安全的。(This cache is per-process (see below) and thread-safe.) 'LOCATION'设置时用于标识独立的内存存储。若是系统只有一个,那么能够忽略该设置。 因为时每一个进程一个缓存实例,因此若是多线程或多进程,那么缓存的使用上就不是很高效,因此该缓存引擎不是很是适合生产环境,适合dev环境。安全
# 经过pip安装 >>> pip install django-redis # 经过pipenv 安装 >>> pyenv install django-redis
CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', 'CONNECTION_POOL_KWARGS': { 'max_connections': 1000 }, # 'PASSWORD': 'xxx', # 若是有设置了redis-server密码在这里设置 } } }
能够查看django_redis.cache.RedisCache 都是继承了from django.core.cache.backends.base import BaseCache ,因此在django中高级的缓存操做都是经过BaseCache中定义的接口。bash
因此自定义cache backend 能够经过继承django.core.cache.backends.base.BaseCache 接口,而后实现接口中的方法。就能够将本身的backend配置到django中使用了。多线程
Tips: 经过redis-cli 查看全部库的key统计信息,命令是info keyspace;ide
# 引入装饰器装饰视图函数便可缓存视图 from django.views.decorators.cache import cache_page
import time from django.views.decoratosr.cache import cache_page @chace_page(60*5) # 必须设置缓存的更新间隔,单位秒 def content_detail(request): return HTTPResponse('hello' + str(time.time()))
在配置文件的中间件列表的首尾分别添加以下中间件:
MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', ...... 'django.middleware.common.CommonMiddleware', ...... 'django.middleware.cache.FetchFromCacheMiddleware',]
{% load cache %} {% cache 500 sidebar %} .. sidebar .. {% endcache %}
经过cache对象的api直接操做缓存。
from django.core.cache import caches #这是全部设置的cache对象的字典 from django.core.cache import cache # 这是”default" 默认的cahce对象 my_cache = caches['mycache'] my_cache.set('k1', 'abc', 30) # 设置k1 值为 ’abc' 有效期 30s.
Note: 注意,每一个process 获取的 cache instance 都是独立的,不是同一个,为保证线程安全。