Created
June 28, 2012 22:29
-
-
Save jtratner/3014398 to your computer and use it in GitHub Desktop.
Memcache mixin
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
class DBCacheMixin(object): | |
""" mixin for datastore objects with cache/key lookups, inheriting classes must define: | |
MCBASE, (optionally NAMESPACE -- though handled internally) """ | |
NAMESPACE = None | |
MCBASE = "NONE_" | |
@classmethod | |
def get_cache(cls, key, base=None, group=None): | |
base = (base or cls.MCBASE) + (group or cls.GROUP) | |
r = memcache.get(key=base + str(key), namespace=cls.NAMESPACE) | |
if r: | |
age, obj = r | |
try: | |
obj.age = age | |
except AttributeError: | |
# means not an object | |
pass | |
return obj | |
else: | |
return None | |
@classmethod | |
def set_cache(cls, key, value, base=None, group=None): | |
base = (base or cls.MCBASE) + (group or cls.GROUP) | |
value = (time.time(), value) | |
return memcache.set(key=base + str(key),value=value, namespace=cls.NAMESPACE) | |
@classmethod | |
def delete_cache(cls, key, base=None, group=None): | |
base = (base or cls.MCBASE) + (group or cls.GROUP) | |
return memcache.delete(key=base + str(key), namespace=cls.NAMESPACE) | |
@webapp2.cached_property | |
def uid(self): | |
return self.key().id() or self.key().name() | |
def cache(self, group=None): | |
return self.set_cache(key=self.uid, value=self, group=group) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment