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

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

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

文档

安装

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

参考文章

猜你喜欢

转载自blog.csdn.net/mouday/article/details/134603402