Skip to content

Instantly share code, notes, and snippets.

@dmateos
Created June 12, 2018 20:45
Show Gist options
  • Save dmateos/5b3d286c4c4dc1b5c48f3798ed0efc59 to your computer and use it in GitHub Desktop.
Save dmateos/5b3d286c4c4dc1b5c48f3798ed0efc59 to your computer and use it in GitHub Desktop.
class CacheTable(object):
def __init__(self, cache):
self.cache = cache
self.row_template = {
"capital" : 0,
"amortised" : 0,
"monthly" : 0,
"costs" : [],
"scenarios" : [],
"dependencies" : 1,
}
def get(self, **kwargs):
if "item" in kwargs:
cached_item = self.cache.get(self.get_key(kwargs["item"]))
if not cached_item:
print("cache miss for {0}".format(self.get_key(kwargs["item"])))
self.set(kwargs["item"])
cached_item = self.get(item=kwargs["item"])[0]
return [cached_item] # Always return a []
if "items" in kwargs:
item_cache = []
for i in kwargs["items"]:
cached_item = self.get(item=i)
if cached_item:
item_cache.append(cached_item[0])
return item_cache
def filter(self, scenarios):
pass
def set(self, item):
customer = item.customer
rows = {}
for month in customer.months():
month_row = dict(self.row_template)
try:
month_row["monthly"] = item.monthcost(month)
except AttributeError:
pass
try:
month_row["costs"] = item.costids()
except AttributeError:
pass
try:
month_row["capital"] = item.capitalcost(month)
except AttributeError:
pass
try:
month_row["dependencies"] = item.dependencies(month)
except AttributeError:
pass
rows[month.strftime("%Y-%m-%d")] = month_row
self.cache.set(self.get_key(item), rows)
return rows
def warm(self, model_array):
for model in model_array:
objs = model.objects.all()
for obj in objs:
self.set(obj)
def get_key(self, item):
return "cost_{0}_{1}".format(type(item).__name__, item.id)
import redis
import pickle
"""
Oh look Morty im a cache, im cache rick
Aww jeeez.
"""
class CacheRick(object):
def __init__(self, host="localhost"):
self.redis = redis.StrictRedis(host, port=6379, db=0)
def get(self, key):
pickled_rick = self.redis.get(key)
if not pickled_rick:
return None
unpickled_rick = pickle.loads(pickled_rick)
return unpickled_rick
def set(self, key, rick):
pickled_rick = pickle.dumps(rick)
self.redis.set(key, pickled_rick)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment