Caching Responses in Python Without External Libraries
O
Ohidur Rahman Bappy
MAR 22, 2025
Caching Responses in Python Without External Libraries
We often need to cache server responses to save time and bandwidth. While there are external libraries available for caching, such as dictttl
, we can achieve caching using Python's built-in features.
Below is a Python implementation using the built-in functools.lru_cache
, which doesn't require any third-party libraries.
Implementing Caching
You can add an additional parameter to your function, ttl_hash=None
. This parameter acts as a "time-sensitive hash," mainly used to affect the lru_cache
.
from functools import lru_cache
import time
@lru_cache()
def my_expensive_function(a, b, ttl_hash=None):
del ttl_hash # to emphasize we don't use it and to quiet pylint
return a + b # simulate a CPU-intensive operation
def get_ttl_hash(seconds=3600):
"""Return the same value within a `seconds` time period."""
return round(time.time() / seconds)
# Example usage in your code...
res = my_expensive_function(2, 2, ttl_hash=get_ttl_hash())
# The cache is updated once an hour
This implementation makes use of lru_cache
to cache the responses, and get_ttl_hash
ensures that the cache refreshes at specified intervals. Use this method to optimize performance without relying on external dependencies.