Skip to content

Instantly share code, notes, and snippets.

@Avlyssna
Created September 30, 2018 19:45
Show Gist options
  • Save Avlyssna/6d89bb3b5078a2f274fe0b8923ef1334 to your computer and use it in GitHub Desktop.
Save Avlyssna/6d89bb3b5078a2f274fe0b8923ef1334 to your computer and use it in GitHub Desktop.
# Standard library imports
from datetime import datetime
from pathlib import Path
from pickle import dumps, loads
class CachedObject:
def __init__(self, value):
self.value = value
self.cached_at = datetime.now()
class Cache:
def __init__(self, cache={}):
self.cache = cache
def get(self, table, key, expires_after=None):
if not self.cache.get(table):
self.cache[table] = {}
item = self.cache[table].get(key)
if item and not (expires_after and item.cached_at + expires_after <= datetime.now()):
return item.value
def put(self, table, key, value):
if not self.cache.get(table):
self.cache[table] = {}
self.cache[table][key] = CachedObject(value)
return value
def save(self, file_name='cache.pkl'):
with open(file_name, 'wb') as file:
file.write(dumps(self.cache))
@classmethod
def load(this, file_name='cache.pkl'):
if Path(file_name).is_file():
with open(file_name, 'rb') as file:
return this(loads(file.read()))
else:
return this()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment