Flask-Cache为实例方法

时间:2018-05-04 05:43:10

标签: python caching flask

我有以下课程:

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":

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 已定义

,因此不会有意义

为什么我一直错过我的缓存命中?

1 个答案:

答案 0 :(得分:0)

实际上我发现我有很多东西要缓存,默认的CACHE_THRESHOLD = 500过快填满,导致很多缓存未命中。

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