2017-07-07 90 views
0

我正在使用Flask-Restful for Python API,它运行良好。 现在,我想要缓存的数据库操作很少,我该怎么做呢?我在网上搜索,有几个选项,如烧瓶缓存和CacheTools,我无法决定。python的缓存建议

Flask缓存主要是关于缓存请求而不是内部使用的数据,纠正我,如果我错了。

Cachetools有像lru_cache等有用的方法,这可能对我有用吗?

PS:我主要是一个Java人,曾经在我以前的服务中使用番石榴和spring启动,所以在python中寻找类似的东西。

+1

瓶颈高速缓存缓存对请求的响应。 lru_cache缓存函数的返回值,CacheTools为您提供了不同的缓存策略,并且您对它们的处理由您决定。我不知道弹簧引导是做什么的,但它取决于你的需求,你想要缓存什么位置和什么,并且没有单一的解决方案。 – syntonym

+0

嗨,我基本上想缓存数据而不是请求,因为我的请求几乎都是唯一的。 – xmen

回答

0

此前,我也有这个问题。最后,我使用Redis。

而在werkeug中,有一个缓存库,这使得Redis易于使用。

from werkzeug.contrib.cache import RedisCache

了解更多信息,请参阅doc

顺便说一句,如果你的应用程序在单一的进程中运行(多线程也行),你可以使用下面的代码。

class CachedItem: 
    def __init__(self, item, duration): 
     self.item = item 
     self.duration = duration 
     self.time_stamp = time.time() 

    def __repr__(self): 
     return '<CachedItem {%s} expires at: %s>' % (self.item, time.time() + self.duration) 


class CachedDict(dict): 
    def __init__(self, *args, **kwargs): 
     super(CachedDict, self).__init__(*args, **kwargs) 
     self.lock = threading.Lock() 

    def get_cache(self, key, default=None, duration=300): 
     with self.lock: 
      self._clean() 
      if key in self: 
       return self[key].item 
      else: 
       self[key] = CachedItem(default, duration) 
      return self[key].item 

    def set_cache(self, key, value, duration=300): 
     with self.lock: 
      self[key] = CachedItem(value, duration) 

    def _clean(self): 
     for key in list(self.keys()): # [self.keys()] error, we get dict_keys type 
      if self[key].time_stamp + self[key].duration <= time.time(): 
       self.pop(key)