You can get all keys with cache._cache.keys()
in reverse order for LocMemCache.
For example, you set 4 cache values as shown below:
from django.core.cache import cache
cache.set("first_name", "John")
cache.set("last_name", "Smith", version=2)
cache.set("age", 36, version=3)
cache.set("gender", "Male")
Then, you can get all the keys with cache._cache.keys()
in reverse order as shown below. *:1:
, :2:
or :3:
before each key indicates version:
from django.core.cache import cache
print(cache._cache.keys())
# odict_keys([':1:gender', ':3:age', ':2:last_name', ':1:first_name'])
And, you can iterate all the keys as shown below:
from django.core.cache import cache
for key in cache._cache.keys():
print(key)
Output:
:1:gender
:3:age
:2:last_name
:1:first_name
And, you can iterate all the keys with the versions as shown below:
from django.core.cache import cache
for key in cache._cache.keys():
new_key = key.split(":", 2)[2]
version = key.split(":", 2)[1]
print(new_key, version)
Output:
gender 1
age 3
last_name 2
first_name 1
Lastly, you can iterate all the key's values which match the keys and versions as shown below. *list() is needed for cache._cache.keys()
otherwise you get error and specifying a version is needed for cache.delete() otherwise you cannot delete all the cache values and the answer of my question explains the default version of a cache value with LocMemCache
:
from django.core.cache import cache
# `list()` is needed
for key in list(cache._cache.keys()):
new_key = key.split(":", 2)[2]
version = key.split(":", 2)[1]
print(cache.get(new_key, version=version))
Output:
Male
36
Smith
John