-
-
Save jvanasco/01af92e100769d52f7b8 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
# example postcache hook | |
if cached_data.photo_id | |
cached_data._lazyload( 'photo', | |
request.cachingApi.get, | |
'object','Photo','get_by_id',(cached_data.photo_id,), | |
) | |
# in the above example, the additional data is not fetched from the cache until cached_data.photo is accessed. |
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 UtilityObject(object): | |
"""SqlAlchemy mapped classes (declaritive) inherit from this""" | |
def columns_as_dict(self): | |
return dict((col.name, getattr(self, col.name)) for col in sqlalchemy_orm.class_mapper(self.__class__).mapped_table.c) | |
class LazyloadedFunction(object): | |
"""cached instance of a function to execute, if needed""" | |
def __init__(self, object , object_attribute, function , *args , **kwargs ): | |
self.object = object | |
self.object_attribute = object_attribute | |
self.function = function | |
self.args = args | |
self.kwargs = kwargs | |
try: | |
self.__doc__ = function.__doc__ | |
except: # pragma: no cover | |
pass | |
def execute(self): | |
val = self.function(*self.args,**self.kwargs) | |
return val | |
class ObjectifiedDict(dict): | |
"""a dict that allows for attribute based access and lazyloaded attributes""" | |
def __getitem__(self,attr): | |
if attr in self: | |
item = dict.__getitem__(self,attr) | |
if isinstance( item , LazyloadedFunction ): | |
item = item.execute() | |
dict.__setitem__( self , attr , item ) | |
return item | |
def __getattr__(self,attr): | |
if attr in self: | |
if isinstance( self[attr] , LazyloadedFunction ): | |
self[attr] = self[attr].execute() | |
return self[attr] | |
return self.__getattribute__(attr) | |
#def __getattribute__(self,attr): | |
# return dict.__getattribute__(self,attr) | |
def _lazyload( self, attr , function , *args , **kwargs ): | |
self[attr] = LazyloadedFunction(self,attr,function,*args,**kwargs) | |
def _expand(self): | |
for k,v in self.iteritems(): | |
if isinstance( v , LazyloadedFunction ) : | |
v = v.execute() | |
dict.__setitem__( self , k , v ) | |
def _cacheable( self , exclude=None ): | |
copied = self.copy() | |
for k,v in copied.iteritems(): | |
if isinstance( v , LazyloadedFunction ) : | |
del copied[k] | |
if exclude : | |
for k in exclude : | |
if k in copied : | |
del copied[k] | |
return copied |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment