简体   繁体   English

python缓存建议

[英]Advice in caching for python

I am using Flask- Restful for a Python API, which is working well. 我将Flask- Restful用于Python API,效果很好。 Now, there are few DB operations which I want to cache, how do I go about that? 现在,我要缓存的数据库操作很少,该如何处理? I have searched online and there were a couple of options like flask cache and CacheTools and I am not able to decide. 我已经在网上搜索过,但是有一些选项,例如flask cache和CacheTools,我无法决定。

Flask cache was mainly about caching the requests rather than the data used inside, correct me if I am wrong. Flask缓存主要是关于缓存请求,而不是内部使用的数据,如果我错了,请纠正我。

Cachetools has useful methods like lru_cache etc. which could be of use to me? Cachetools具有有用的方法,如lru_cache等,可能对我有用?

PS: I am primarily a Java guy and used to use guava with spring boot in my previous services, so looking for something like that in python. PS:我主要是Java的人,以前在以前的服务中曾使用guava和spring boot,所以在python中寻找类似的东西。

Earlier, I had this problem, too. 之前,我也有这个问题。 In the end, I use Redis. 最后,我使用Redis。

And in werkeug , there is a cache lib, which makes Redis easy to use. werkeug ,有一个缓存库,使Redis易于使用。

from werkzeug.contrib.cache import RedisCache

for more information, see the doc 有关更多信息,请参阅文档

By the way, if your app runs in single process(multithread is also OK), you can just use the codes below. 顺便说一句,如果您的应用程序在单个进程中运行(也可以使用多线程),则可以使用以下代码。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM