django做后端cache

在django进行后端缓存十分方便,自带组件,支持本地内存,redis,memcache等。为了稳定和快速,建议用本地memcache

django缓存采用decorator的形式,不用改逻辑代码,无侵入

  1. 首先在setting里加入
    # 在setting里加配置
    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
            'LOCATION': '127.0.0.1:11211',
        }
    }

     

  2. views里加decorator
    from django.views.decorators.cache import cache_page
    
    # 给下面这个方法加上一个开头为prefix定义的key,过期时间15分钟
    
    @cache_page(60 * 15, key_prefix="date_guest_video_info_list")
     def guest_video_info_list(request):
       ...

     

  3. 在memcache里查看key
    xxxx$ telnet localhost 11211
    Trying 127.0.0.1...
    Connected to localhost.
    Escape character is '^]'.
    
    stats items
    STAT items:4:number 32
    STAT items:4:age 6827
    STAT items:4:evicted 0
    ...
    
    stats cachedump 22 100
    ITEM :1:views.decorators.cache.cache_page.data_xxx.GET.d4b41e219b49d5239ca325442fc6a590.d41d8cd98f00b204e9800998ecf8427e.en-us.UTC [10125 b; 1506574553 s]
    END

     

可见非常方便地对request做了hash后做key存储,并且有ttl

posted @ 2017-09-28 17:34  Els0n  阅读(243)  评论(0编辑  收藏  举报