socketify.py/examples/helpers/memory_cache.py

28 wiersze
663 B
Python
Czysty Zwykły widok Historia

2022-06-01 13:29:35 +00:00
import datetime
2022-11-16 19:28:46 +00:00
2022-06-01 13:29:35 +00:00
class MemoryCacheItem:
def __init__(self, expires, value):
self.expires = datetime.datetime.utcnow().timestamp() + expires
self.value = value
2022-11-16 19:28:46 +00:00
2022-06-01 13:29:35 +00:00
def is_expired(self):
return datetime.datetime.utcnow().timestamp() > self.expires
2022-11-16 19:28:46 +00:00
2022-06-01 13:29:35 +00:00
class MemoryCache:
def __init__(self):
self.cache = {}
def setex(self, key, expires, value):
self.cache[key] = MemoryCacheItem(expires, value)
2022-11-16 19:28:46 +00:00
2022-06-01 13:29:35 +00:00
def get(self, key):
try:
cache = self.cache[key]
if cache.is_expired():
return None
return cache.value
except KeyError:
2022-11-16 19:28:46 +00:00
return None