代码之家  ›  专栏  ›  技术社区  ›  Stavros Korokithakis

有Python缓存库吗?[闭门]

  •  96
  • Stavros Korokithakis  · 技术社区  · 17 年前

    我正在寻找Python缓存库,但到目前为止找不到任何东西。我需要一个简单的 dict -就像一个接口,我可以在其中设置密钥和它们的过期时间,并将它们恢复缓存。有点像:

    cache.get(myfunction, duration=300)
    

    它将从缓存中获取项目(如果它存在),或者调用函数并存储它(如果它不存在或已过期)。有人知道这样的事吗?

    12 回复  |  直到 17 年前
        1
  •  79
  •   j13r    10 年前

    在Python3.2中,您可以使用decorator @lru_cache 从functools库中。 它是最近使用的缓存,因此其中的项目没有过期时间,但作为一种快速攻击,它非常有用。

    from functools import lru_cache
    
    @lru_cache(maxsize=256)
    def f(x):
      return x*x
    
    for x in range(20):
      print f(x)
    for x in range(20):
      print f(x)
    
        3
  •  28
  •   tgray    17 年前

    你也可以看看 Memoize decorator . 你可能不需要太多的修改就可以让它做你想做的事情。

        4
  •  14
  •   NuclearPeon    12 年前

    还没有人提到搁置。 https://docs.python.org/2/library/shelve.html

    它不是memcached,但看起来更简单,可能适合您的需要。

        5
  •  14
  •   Michael Delgado    6 年前

    乔布里 https://joblib.readthedocs.io 支持Memoize模式中的缓存功能。主要的想法是缓存计算代价高昂的函数。

    >>> from joblib import Memory
    >>> mem = Memory(cachedir='/tmp/joblib')
    >>> import numpy as np
    >>> square = mem.cache(np.square)
    >>> 
    >>> a = np.vander(np.arange(3)).astype(np.float)
    >>> b = square(a)                                   
    ________________________________________________________________________________
    [Memory] Calling square...
    square(array([[ 0.,  0.,  1.],
           [ 1.,  1.,  1.],
           [ 4.,  2.,  1.]]))
    ___________________________________________________________square - 0...s, 0.0min
    
    >>> c = square(a)
    

    您还可以在函数上使用@memory.cache decorator等奇特功能。文件如下: https://joblib.readthedocs.io/en/latest/generated/joblib.Memory.html

        6
  •  9
  •   David Berger    17 年前

    the python memcached API 是流行的工具,但我自己没有使用过,也不确定它是否支持您需要的功能。

        7
  •  7
  •   Tzury Bar Yochay    17 年前
    import time
    
    class CachedItem(object):
        def __init__(self, key, value, duration=60):
            self.key = key
            self.value = value
            self.duration = duration
            self.timeStamp = time.time()
    
        def __repr__(self):
            return '<CachedItem {%s:%s} expires at: %s>' % (self.key, self.value, time.time() + self.duration)
    
    class CachedDict(dict):
    
        def get(self, key, fn, duration):
            if key not in self \
                or self[key].timeStamp + self[key].duration < time.time():
                    print 'adding new value'
                    o = fn(key)
                    self[key] = CachedItem(key, o, duration)
            else:
                print 'loading from cache'
    
            return self[key].value
    
    
    
    if __name__ == '__main__':
    
        fn = lambda key: 'value of %s  is None' % key
    
        ci = CachedItem('a', 12)
        print ci 
        cd = CachedDict()
        print cd.get('a', fn, 5)
        time.sleep(2)
        print cd.get('a', fn, 6)
        print cd.get('b', fn, 6)
        time.sleep(2)
        print cd.get('a', fn, 7)
        print cd.get('b', fn, 7)
    
        8
  •  6
  •   Magentron    10 年前

    你可以用我的简单方法解决这个问题。这真是直截了当,没有什么特别之处:

    class MemCache(dict):
        def __init__(self, fn):
            dict.__init__(self)
            self.__fn = fn
    
        def __getitem__(self, item):
            if item not in self:
                dict.__setitem__(self, item, self.__fn(item))
            return dict.__getitem__(self, item)
    
    mc = MemCache(lambda x: x*x)
    
    for x in xrange(10):
        print mc[x]
    
    for x in xrange(10):
        print mc[x]
    

    它确实缺少过期函数性,但您可以通过在MemCache c-tor中指定特定规则来轻松扩展它。

    希望代码是足够自解释的,但如果不是的话,只需提及,缓存正在作为其c-tor参数之一传递一个转换函数。它反过来用于生成有关输入的缓存输出。

        9
  •  5
  •   harry    15 年前

    试试redis,它是应用程序以原子方式共享数据或使用web服务器平台共享数据的最干净、最简单的解决方案之一。它非常容易安装,您将需要一个python redis客户端 http://pypi.python.org/pypi/redis

        10
  •  2
  •   neuro    7 年前

    看看 gocept.cache 在pypi上,管理超时。

        11
  •  2
  •   Community Mohan Dere    6 年前

    这 project

    项目页面中的一些信息:

    pip安装缓存

    用法:

    import pylibmc
    from cache import Cache
    
    backend = pylibmc.Client(["127.0.0.1"])
    
    cache = Cache(backend)
    
    @cache("mykey")
    def some_expensive_method():
        sleep(10)
        return 42
    
    # writes 42 to the cache
    some_expensive_method()
    
    # reads 42 from the cache
    some_expensive_method()
    
    # re-calculates and writes 42 to the cache
    some_expensive_method.refresh()
    
    # get the cached value or throw an error
    # (unless default= was passed to @cache(...))
    some_expensive_method.cached()
    
        12
  •  0
  •   Jens W. Klein    16 年前
        13
  •  0
  •   Hoda    6 年前

    ExpiringDict是另一个选项:

    https://pypi.org/project/expiringdict/

        14
  •  -6
  •   warvariuc    13 年前

    keyring.set_password("service","jsonkey",json_res)
    
    json_res= keyring.get_password("service","jsonkey")
    
    json_res= keyring.core.delete_password("service","jsonkey")