Quickstart¶
Eager to get started? This page gives a good introduction to CacheLib. Follow Installation to set up a project and install CacheLib first.
A Minimal Example¶
A minimal example of using SimpleCache from CacheLib
looks like this:
from cachelib import SimpleCache
# Create a cache instance
cache = SimpleCache()
# Set a value in the cache
cache.set('my_key', 'my_value')
# Retrieve the value from the cache
value = cache.get('my_key')
print(value) # Output: my_value
# Delete the value from the cache
cache.delete('my_key')
# Try to retrieve the deleted value
value = cache.get('my_key')
print(value) # Output: None
The code above does the following:
Import the
SimpleCacheclass from thecachelibmodule.Create a cache instance using
cache = SimpleCache().Set a value in the cache with the key
'my_key'and the value'my_value'using theSimpleCache.set()method.Retrieve the value from the cache using the
SimpleCache.get()method.Print the retrieved value, which outputs
my_value.Delete the value from the cache using the
SimpleCache.delete()method.Retrieve the deleted value again, which returns
Nonesince it has been removed from the cache.
This example uses the SimpleCache backend. CacheLib
supports multiple backends, such as RedisCache,
MemcachedCache, and more. Each backend is used
the same way by creating an instance of the desired cache class.
To run the application, use python quickstart.py.
The output shows the retrieved value and None for the deleted key.
$ python quickstart.py
my_value
None