The cache.memoize
decorator is nice, but diskcache
also provides us an API that gives us a bit more control as well as more features.
from diskcache import Cache
cache = Cache("local")
# Fetch the result
result = fetch_starwars_person(1)
# Put it in the cache
cache.set(1, result)
# Fetch it
cache.get(1)
# Fetch and remove
cache.pop(1)
There are some extra features available here too. Like incrementing/decrementing:
cache.set("a", 1)
cache.incr("a")
# Returns 2
cache.incr("a")
# Returns 3
cache.decr("a")
# Returns 2
If you like, you can also use the cache
as if it is a dictionary, should you prefer that syntax.
cache["a"]
# Returns 3
cache["a"] = 1
cache["a"]
# Returns 1
"a" in cache
# Returns True
del cache["a"]
# Deletes the `a` key from the cache