DiskCache is disk and file based cache library, written in pure-Python. Authors of this library claim that DiskCache performs faster than Memcache and Redis libraries. And, they have shown benchmark results with comparison.
DiskCache has several features which are:
- Fully documented
- 100% test coverage
- Django compatible API
- Thread-safe and process-safe
- Supports multiple eviction policies (LRU and LFU included)
- Keys support “tag” metadata and eviction
How to install #
Installing DiskCache can be done with using
$ pip install diskcache
Usage Example #
Save some keys into cache.
>>> import diskcache as dc >>> cache = dc.Cache('tmp') >>> cache.set(b'foo1') = b'bar1' >>> cache.set(b'foo2') = b'bar2' >>> cache.close()
Retrieve values from cache.
>>> import diskcache as dc >>> cache = dc.Cache('tmp') >>> value = cache.get(b'foo1')
There’s also a set method with additional keyword parameters:
>>> from io import BytesIO >>> cache.set(b'key', BytesIO('value'), expire=5, read=True, tag=u'data') True
In the example above: the key expires in 5 seconds, the value is read as a file-like object, and tag metadata is stored with the key. Another method, get supports querying extra information with default, read, expire_time, and tag keyword parameters.
>>> cache.get(b'key', default=b'', read=True, expire_time=True, tag=True) (<_io.BufferedReader name=u'/tmp/mycachedir/1d/6e/128a921c3b8a9027c1f69989f3ac.val'>, 1457066214.784396, u'data')
In Python, we can do better. And we can do it in pure-Python!
In : import pylibmc In : client = pylibmc.Client(['127.0.0.1'], binary=True) In : client[b'key'] = b'value' In : %timeit client[b'key'] 10000 loops, best of 3: 25.4 µs per loop In : import diskcache as dc In : cache = dc.Cache('tmp') In : cache[b'key'] = b'value' In : %timeit cache[b'key'] 100000 loops, best of 3: 11.8 µs per loop