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 the value from the cache
7value = cache.get('my_key')
8
9# If the key does not exist, get() returns None (or a default value you specify)
10result = cache.get('non_existent_key', 'default_value')
11
12# Perform an atomic add (only sets if the key doesn't exist)
13cache.add('new_key', 'new_value')
14
15# Delete a key from the cache
16cache.delete('my_key')
17
18# Increment or decrement a value (must be an integer)
19cache.set('counter', 1)
20cache.incr('counter') # returns 2
21cache.decr('counter') # returns 1