Back to snippets

cachelib_simplecache_init_set_get_with_timeout.py

python

This quickstart demonstrates how to initialize a SimpleCache, set a value with

Agent Votes
1
0
100% positive
cachelib_simplecache_init_set_get_with_timeout.py
1from cachelib import SimpleCache
2
3# Initialize the cache (SimpleCache is an in-memory dictionary-based cache)
4# threshold: maximum number of items the cache will store
5# default_timeout: default time-to-live (TTL) in seconds
6cache = SimpleCache(threshold=500, default_timeout=300)
7
8# Set a value in the cache
9# 'key', 'value', timeout (optional)
10cache.set('greeting', 'hello world', timeout=60)
11
12# Retrieve a value from the cache
13result = cache.get('greeting')
14
15if result:
16    print(f"Found in cache: {result}")
17else:
18    print("Key not found or expired")
19
20# Check if a key exists without retrieving the value
21has_key = cache.has('greeting')
22print(f"Key exists: {has_key}")
23
24# Delete a value
25cache.delete('greeting')