我有以下结构的多个类:
class Thing(Base):
id = Column(Integer, primary_key=True)
@cache_region('short_term', 'get_children')
def get_children(self, childrentype=None):
return DBSession.query()...
然而问题是,烧杯会将get_children()缓存在同一个区域而不管自身,使得缓存毫无意义。黑客是:
def get_children(self, id, childrentype=None):
...
children = thing.get_children(thing.id, 'asdf')
但每次调用方法时传递Thing.id都很难看。我想使用cache.region作为常规函数而不是装饰器,但我找不到任何文档。有点像:
def get_children(self, childrentype=None):
if "cached in cache_region(Thing.get_children, 'short_term', 'get_children', self.id, childrentype)":
return "the cache"
else:
query = DBSession.query()...
"cache query in cache_region(Thing.get_children', 'short_term', 'get_children', self.id, childrentype)"
return query
甚至更棒的是:
@cache_region('short_term', 'get_children', self.id)
def get_children(self, childrentype=None):
...
最好的方法是什么?
答案 0 :(得分:3)
我迟钝了。我应该做的事情如下:
class Thing(Base):
id = ...
def get_children(self, childrentype, invalidate=False):
if invalidate:
region_invalidate(_get_children, None, self.id, childrentype)
@cache_region('short_term', 'get_children')
def _get_children(id, childrentype):
...
return query
return _get_children(self.id, childrentype)
当然,如果我不必在该方法中定义另一个函数会更好,但这很简单。