有一个Python缓存库吗?

时间:2009-09-15 13:42:58

标签: python caching

我正在寻找一个Python缓存库但到目前为止找不到任何东西。我需要一个简单的dict - 类似的接口,我可以设置密钥及其过期,并让它们重新缓存。类似的东西:

cache.get(myfunction, duration=300)

如果它存在,它将从缓存中提供该项目,或者如果它没有或已经过期则调用该函数并存储它。有谁知道这样的事情?

14 个答案:

答案 0 :(得分:57)

从Python 3.2中,您可以使用functools库中的装饰器@lru_cache。 它是最近使用的缓存,因此其中的项目没有到期时间,但作为快速入侵它非常有用。

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)

答案 1 :(得分:46)

答案 2 :(得分:27)

您也可以查看Memoize decorator。你可以在没有太多修改的情况下让它做你想做的事。

答案 3 :(得分:14)

Joblib http://packages.python.org/joblib/支持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装饰器。文档在这里:http://packages.python.org/joblib/memory.html

答案 4 :(得分:12)

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

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

答案 5 :(得分:9)

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

答案 6 :(得分:7)

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)

答案 7 :(得分:5)

尝试使用redis,它是应用程序以原子方式共享数据或者如果您有一些Web服务器平台的最干净,最简单的解决方案之一。它很容易设置,你需要一个python redis客户端http://pypi.python.org/pypi/redis

答案 8 :(得分:4)

您可以使用我的简单解决方案来解决问题。它真的很简单,没什么特别的:

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 :(得分:2)

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

答案 10 :(得分:2)

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()

答案 11 :(得分:0)

查看bda.cache http://pypi.python.org/pypi/bda.cache - 使用ZCA并使用zope和bfg进行测试。

答案 12 :(得分:0)

ExpiringDict是另一种选择:

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

答案 13 :(得分:-4)

keyring是最好的python缓存库。你可以使用

keyring.set_password("service","jsonkey",json_res)

json_res= keyring.get_password("service","jsonkey")

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