使用装饰器给属性设置过期时间

ref:

https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76

下面实现了一个装饰器类,可以用它来给别的属性设置过期时间

import time

class cached_property(object):

    def __init__(self, ttl=None):
        print 'initing...'
        self.ttl = ttl

    def prepare_func(self, func, doc=None):
        '''Prepare to cache object method.'''
        print 'prepare_func...'
        self.func = func
        self.__doc__ = doc or func.__doc__
        self.__name__ = func.__name__
        self.__module__ = func.__module__

    def __call__(self, func, doc=None):
        print 'calling...'
        self.prepare_func(func, doc)
        return self

    def __get__(self, obj, cls):
        print 'getting...', obj, cls, self.__name__
        if obj is None:
            return self

        now = time.time()
        try:
            value, last_update = obj._cache[self.__name__]
            if self.ttl and self.ttl > 0 and now - last_update > self.ttl:
                raise AttributeError
        except (KeyError, AttributeError):
            value = self.func(obj)
            try:
                cache = obj._cache
            except AttributeError:
                cache = obj._cache = {}
            cache[self.__name__] = (value, now)

        return value

    def __delattr__(self, name):
        pass

    def __set__(self, obj, value):
        print 'setting...'
        try:
            cache = obj._cache
        except AttributeError:
            cache = obj._cache = {}
        now = time.time()
        cache[self.__name__] = (value, now)


    def __delete__(self, obj):
        print 'deleting...'
        try:
            cache = obj._cache
        except AttributeError:
            cache = obj._cache = {}
        cache.pop(self.__name__, None)

Test Case:

# verify get
tc = TestCache('Jack')
print tc.info
tc.name = 'Rose'
print tc.info

# verify set
tc0 = TestCache('Jack')
print tc0.info
tc0.info = 'Rose'
print tc0.info

# verify del
tc0 = TestCache('Jack')
print tc0.info
del tc0.info
print tc0.info

 

posted @ 2018-08-06 15:42  geeklove  阅读(266)  评论(0)    收藏  举报