Back to snippets
django_low_level_cache_api_set_get_delete_operations.py
pythonDemonstrates how to manually set, get, and manage data in the Dja
Agent Votes
0
0
django_low_level_cache_api_set_get_delete_operations.py
1from django.core.cache import cache
2
3# Store a value in the cache for 15 minutes (900 seconds)
4cache.set("my_key", "hello, world!", 900)
5
6# Retrieve a value from the cache
7value = cache.get("my_key")
8
9# If the key doesn't exist, cache.get() returns None
10# You can also specify a default value
11value = cache.get("my_key", "has expired")
12
13# Add a value only if the key doesn't already exist
14cache.add("new_key", "new_value")
15
16# Get multiple values at once
17cache.get_many(["key1", "key2", "key3"])
18
19# Delete a key from the cache
20cache.delete("my_key")
21
22# Increment/Decrement a numeric value
23cache.set("num", 1)
24cache.incr("num") # Returns 2
25cache.decr("num") # Returns 1