With set(), set_many(), get(), get_many() and get_or_set(), you can set and get cache values with LocMemCache which is used by default as shown below. *set()
can set a timeout and a version and set_many()
can set multiple cache values with a timeout and get()
can get the key's cache value matched with the version and get a default value if the key doesn't exist and get_many()
can get multiple cache values and get_or_set()
can get a key's cache value if the key exists or set and get a key's cache value if the key doesn't exist and my answer explains how to delete cache values with LocMemCache
and the answer of my question explains the default version of a cache value with LocMemCache
:
from django.http import HttpResponse
from django.core.cache import cache
def test(request):
cache.set("first_name", "John")
cache.set("first_name", "David", 30, 2)
cache.set("last_name", "Smith")
cache.set("last_name", "Miller", version=2)
cache.set_many({"age": 36, "gender": "Male"}, 50)
print(cache.get("first_name")) # John
print(cache.get("first_name", version=2)) # David
print(cache.get("first_name", "Doesn't exist", version=3)) # Doesn't exist
print(cache.get_many(["first_name", "last_name", "age", "gender"]))
# {'first_name': 'John', 'last_name': 'Smith', 'age': 36, 'gender': 'Male'}
print(cache.get_many(["first_name", "last_name", "age", "gender"], 2))
# {'first_name': 'David', 'last_name': 'Miller'}
print(cache.get_or_set("first_name", "Doesn't exist")) # John
print(cache.get_or_set("email", "Doesn't exist")) # Doesn't exist
return HttpResponse("Test")