Created
January 19, 2015 06:18
-
-
Save hirokiky/58f3a5de5998c3362e44 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" Cache <-> Object Mapper | |
I know there is `rom <https://pypi.python.org/pypi/rom>`_ or some. | |
""" | |
import json | |
from django.core.cache import cache | |
SEPARATOR = ':' | |
class CacheModel(object): | |
key_attribute = '' | |
attribute_names = () | |
def __init__(self, **kwargs): | |
for attr in self.attribute_names: | |
init_value = kwargs.get(attr, None) | |
setattr(self, attr, init_value) | |
@classmethod | |
def generate_key(cls, key_value): | |
class_name = cls.__name__ | |
module_name = __name__ | |
return module_name + '.' + class_name + SEPARATOR + key_value | |
@property | |
def key(self): | |
return self.generate_key(getattr(self, self.key_attribute)) | |
@staticmethod | |
def serialize(obj): | |
return json.dumps(obj) | |
@staticmethod | |
def deserialize(dumped): | |
return json.loads(dumped) | |
@property | |
def attributes(self): | |
return {attr: getattr(self, attr, None) for attr in self.attribute_names} | |
@classmethod | |
def get(cls, key): | |
dumped = cache.get(cls.generate_key(key)) | |
return cls.deserialize(dumped) | |
def save(self): | |
dumped = self.serialize(self.attributes) | |
return cache.set(self.key, dumped) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment