0
点赞
收藏
分享

微信扫一扫

Python:diskcache实现基于文件的数据缓存

diskcache是一个基于Sqlite文件的数据缓存

如果在不想使用redis作为缓存的情况下,可以使用diskcache替代,减少对redis的依赖

文档

  • https://grantjenks.com/docs/diskcache/
  • https://github.com/grantjenks/python-diskcache
  • https://pypi.org/project/diskcache/

安装

pip install diskcache

示例

from diskcache import Cache

# 指定文件夹
cache = Cache('./cache')

# 存
cache.set('name', 'tom')

# 取
print(cache.get('name'))

可以看到,目录下生成了3个文件

$ tree cache
cache
├── cache.db
├── cache.db-shm
└── cache.db-wal

设置过期时间

import time

from diskcache import Cache


# 指定文件夹
cache = Cache('./cache')

# 存,单位:秒s
cache.set('name', 'tom', expire=1)

# 取
time.sleep(2)
print(cache.get('name'))
# None

参考文章

  • Python 爬虫进阶篇——diskcache缓存
举报

相关推荐

0 条评论