全面了解django的缓存机制及使用方法

yipeiwu_com6年前Python基础

一、缓存目的

1、减小过载

2、避免重复计算

3、提高系统性能

二、如何进行缓存

三、缓存类型

四、缓存粒度分类

五、缓存的设置与使用

示例一:

CACHES = {  
  'default': {
      'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 
      'LOCATION': '127.0.0.1:11211',  
  }
}

示例二:

CACHES = {  
  'default': {    
    'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 
     'LOCATION': 'unix:/tmp/memcached.sock',  
  }
}

示例三:

CACHES = {  <br>  'default': {    <br>    'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',    <br>    'LOCATION': [      <br>      '172.19.26.240:11211',      <br>      '172.19.26.242:11211',    <br>    ]  <br>  }<br>}

示例四:

CACHES = {  
  'default': {    
    'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',    
    'LOCATION': [      
      '172.19.26.240:11211',      
      '172.19.26.242:11212',      
      '172.19.26.244:11213',    
    ]  
  }
}

访问缓存:

>>>from django.core.cache import caches
>>>cache1 = caches[‘myalias']
>>>cache2 = caches[‘myalias']
>>>cache1 is cache2
True



>>>from django.core.cache import cache
>>>cache.set(‘my_key', ‘hello, world', 30)
>>>cache.get(‘my_key')
‘hello, world!'
>>>cache.get(‘my_key')
None
>>>cache.get(‘my_key',‘has expired')
‘has expired'

六、缓存原理

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python使用PyGame播放Midi和Mp3文件的方法

本文实例讲述了python使用PyGame播放Midi和Mp3文件的方法。分享给大家供大家参考。具体实现方法如下: ''' pg_midi_sound101.py play midi...

设计模式中的原型模式在Python程序中的应用示例

原型模式: 原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。 原型模式本质就是克隆对象,所以在对象初始化操作比较复杂的情况下,很实用,能大大降低耗时,提高性能,因为“不用重...

python导入时小括号大作用

在导入Python模块时,我们可以用 import os 也可以用 from os import * 当然,不推荐第二种方法,这样,会导入太多的os模块内的函数,所以...

线程和进程的区别及Python代码实例

线程和进程的区别及Python代码实例

在程序猿的世界中,线程和进程是一个很重要的概念,很多人经常弄不清线程和进程到底是什么,有什么区别,本文试图来解释一下线程和进程。首先来看一下概念: 进程(英语:process),是计算机...

python创建临时文件夹的方法

本文实例讲述了python创建临时文件夹的方法。分享给大家供大家参考。具体实现方法如下: import tempfile, os tempfd, tempname = tempfi...