Having the ability to set expiration times for keys can be especially useful in scenarios where your data's relevance diminishes over time, like in stock market data, weather forecasts, or caching scenarios. This approach is often found in databases like Redis, and we'll be incorporating it into our own store.
Take for example, monitoring the stock price of a company: if you're tracking Apple Inc. (AAPL) and set a 10-second expiration on the data, a subsequent retrieval after this duration would indicate the data has already expired, necessitating a fresh fetch of the current stock price. This ensures that you're working with the most recent and relevant data and not stale information
In Python, we can extend the built-in dict
type to develop a dictionary which allows us to set an expiry time for keys. Whenever we attempt to retrieve a key, we check if the current time is later than the expiry time for that key. If it is, we delete the key and raise a KeyError
, otherwise we return the key's value. Thus, the basic logic to set the value with an expiration time includes additional steps.
Here's Python logic of how we might implement this expiration feature. The code demonstrates how if we try to access the 'AAPL' key in our ExpiringDict
after its expiry time of 10 seconds, we get a 'Key expired' message.
Let's run this code to simulate key expiration in our key-value store.
xxxxxxxxxx
if __name__ == '__main__':
import time
class ExpiringDict(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.expiry_times = {}
def __setitem__(self, key, value, expiry=None):
super().__setitem__(key, value)
if expiry:
self.expiry_times[key] = time.time() + expiry
def __getitem__(self, key):
if key in self.expiry_times and time.time() > self.expiry_times[key]:
self.__delitem__(key)
raise KeyError
else:
return super().__getitem__(key)
cache = ExpiringDict()
cache['AAPL'] = 150, 10
time.sleep(11)
try:
print(cache['AAPL'])
except KeyError:
print('Key expired')