Django cache简单实现

参考:
官方文档 https://docs.djangoproject.com/en/1.10/topics/cache/
教程 http://www.ziqiangxuetang.com/django/django-cache.html
博文 http://blog.sina.com.cn/s/blog_4980c1e60100082b.html

from django.shortcuts import render
from django.views.decorators.cache import cache_page

@cache_page(60 * 15) # 秒数,这里指缓存 15 分钟,不直接写900是为了提高可读性
def index(request):
    # 读取数据库等 并渲染到网页
    return render(request, 'index.html', {'queryset':queryset})

当使用了cache后,访问情况变成了如下:
访问一个网址时, 尝试从 cache 中找有没有缓存内容
如果网页在缓存中显示缓存内容,否则生成访问的页面,保存在缓存中以便下次使用,显示缓存的页面。

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文件:

 MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.middleware.cache.CacheMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.doc.XViewMiddleware',  
    'django.contrib.flatpages.middleware.\
    FlatpageFallbackMiddleware',
    'django.middleware.gzip.GZipMiddleware',
 )

settings.py文件中的
django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware'之下,因为此处两个文件都会往request中写入相应的数据。此处针对配置全站缓存还必须指定默认的缓存时间CACHE_MIDDLEWARE_SECONDS值及CACHE_MIDDLEWARE_KEY_PREFIX值(可选)。

 CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True

添加以上配置,此功能是配置全站缓存时有关匿名用户和登陆了的用户视图是否从缓存中读取并显示,如果是True,即登陆用户读的数据不会从缓存中读取。此选项针对视图进行缓存配置时同样奏效。
实现cache的编码实现:

针对全站缓存无需进行任何编码实现,针对试图及数据的缓存稍有区别,可能最具可观性的还算是针对数据的缓存,详见以下编码实现:
针对数据编码实现:

  from django.core.cache import cache
  #存储缓存数据
  cache.set('cache_key',data,60*15)#cache_key为存储在缓存中的唯一值,data为存储的数据,60*15为缓存数据的时间
  #获取缓存数据
  cache.get('cache_key',None)#cache_key为储存缓存数据的唯一值

针对视图编码实现:

  from django.views.decorators.cache import cache_page
  def BaCreate(request)
      ....
  BaCreate = cache_page(BaCreate,60*9)

猜你喜欢

转载自blog.csdn.net/vic_torsun/article/details/69389003