如何在类方法中使用beaker缓存区域,而不是作为装饰器?

0 投票
1 回答
512 浏览
提问于 2025-04-17 08:53

我有多个类,结构如下:

class Thing(Base):
    id = Column(Integer, primary_key=True)

    @cache_region('short_term', 'get_children')
    def get_children(self, childrentype=None):
        return DBSession.query()...

不过,问题是,beaker会在同一个区域缓存get_children(),而不管self是什么,这样就让缓存变得没什么意义。一个变通的方法是:

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):
    ...

那么,最好的方法是什么呢?

1 个回答

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)

当然,如果我不需要在那个方法里再定义一个函数,那会更好,但这样也简单得多。

撰写回答