赞
踩
上篇文章我们介绍了本地文件缓存的方法,这次我们说一下django缓存API的使用方法,有时候我们并不需要去缓存一整张视图或函数,我们只需要缓存一个或几个结果数据,这时候我们就可以使用缓存API
下面咱们看一下缓存API的用法:
cache.set()(键,值,超时=DEFAULT_TIMEOUT,版本=无)
cache.get()(键,默认=无,版本=无)
key应该是sty, 并且value可以是任何可挑选的 Python 对象。
该timeout参数是可选的,默认为设置timeout中适当后端的参数。这是应存储在缓存中的秒数 如果缓存中不存在对象,则cache.get()返回None:
如果确定缓存中存入了None值,可以使用哨兵对象来进行判断
- sentinel = object()
- cache.get('my_key', sentinel) is sentinel
- False
-
- cache.get('my_key', sentinel) is sentinel
- True
cache.get 还可以指定如果缓存中不存在对象时要返回的值
cache.get('查询key', '自定义返回值')
cache.add(键,值,超时=DEFAULT_TIMEOUT,版本=无) 它采用与 相同的参数set(),但如果指定的键已经存在,它将不会尝试更新缓存 cache.delete(键,版本=无)
cache.delete_many(键,版本=无)批量删除,可以获取键列表
cache.clear()清除所有键
cache.close() 关闭与缓存的连接。
接着看下在项目中的实际使用:
- from django.core.cache import cache
-
-
- # 存储指定的值到本地缓存中,存储时间为五分钟
-
- def __handle(self):
- for record in self.__kafka_consumer:
- logger.debug(record)
- value = json.loads(record.value)
- cache.set('my_key', value, 60 * 5)
- value['node_id'] = int(NodeID)
- self.__elasticsearch_client.index(
- index=self.__elasticsearch_index,
- doc_type='_doc',
- body=value
- )
- # 获取存入的键值
-
- request = cache.get('my_key')
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreBlack.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。