首页 > 解决方案 > Flask-Cache 不断丢失实例方法的缓存

问题描述

我有以下课程:

class Account(db.Model):
    __tablename__ = 'accounts'
    __versioned__ = {
        'exclude': ['VPSs']
    }

    id = db.Column(db.Integer, primary_key=True)

    def __repr__(self):
        return "%s(%s)" % (self.__class__.__name__, self.id)

    @property
    @cache.memoize(timeout=86400)
    def days_to_topup(self):
        """Rather than using inline model form, just reflect this
        """
        return self.vendor.days_to_topup

我有一种感觉,我根本没有命中缓存。所以我在我的库文件中添加了以下内容:

def get(self, key):
    try:
        expires, value = self._cache[key]
        if expires == 0 or expires > time():
            return pickle.loads(value)
    except (KeyError, pickle.PickleError):
        print("Key missing: %s" % key)
        return None

第一次访问此方法时,我看到控制台中打印了以下内容:

Key missing: portal.account.models.Account.days_to_topup.Account25_memver
Key missing: pAZujNOzo2JX6Tz6T4O3UdS7nzAw
Key missing: portal.account.models.Account.days_to_topup.Account24_memver
Key missing: s3GWC1YnjUGIW/QDT4O3UdwsxOfQ
Key missing: HHb45l3zEGDTepyCT4O3UdTninm7
Key missing: portal.account.models.Account.days_to_topup.Account20_memver
Key missing: tW0ezIHoB3mRHHd4T4O3UduywXbT
Key missing: portal.account.models.Account.days_to_topup.Account19_memver
Key missing: 73KXuVicSsFECnXcT4O3UdDYt/2Z

...

然后我决定再次访问此方法,我意识到我看到了相同的“缺少密钥”:

Key missing: portal.account.models.Account.days_to_topup.Account25_memver
Key missing: pAZujNOzo2JX6Tz6njTvFgk2N2jF
Key missing: portal.account.models.Account.days_to_topup.Account24_memver
Key missing: s3GWC1YnjUGIW/QDnjTvFg2r/Ip2
Key missing: portal.account.models.Account.days_to_topup.Account22_memver
Key missing: HHb45l3zEGDTepyCnjTvFgU/EEE6
Key missing: portal.account.models.Account.days_to_topup.Account20_memver
Key missing: tW0ezIHoB3mRHHd4njTvFgQpKev8
Key missing: portal.account.models.Account.days_to_topup.Account19_memver

所以我不明白为什么@cache.memoization 没有按预期工作。

起初我以为是因为变量self不断变化,但这没有意义,因为我已经定义了repr

为什么我总是错过我的缓存命中?

标签: pythoncachingflask

解决方案


实际上,我发现我有太多要缓存的东西,以至于默认的 CACHE_THRESHOLD=500 被填得太快,导致很多缓存未命中。

将 THRESHOLD 增加到更大的值解决了我的问题


推荐阅读