从python中cacheout模块的Cache()方法获取数据缓存的时间

Posted

技术标签:

【中文标题】从python中cacheout模块的Cache()方法获取数据缓存的时间【英文标题】:Get the time that data was cached at from Cache() method of cacheout module in python 【发布时间】:2021-12-30 15:42:35 【问题描述】:

我正在使用cacheout 来处理我的缓存,因为我在使用缓存工具对 pandas df 进行缓存时遇到了问题。我阅读了文档,但找不到查看缓存何时创建或到期的方法。是否可以检索这些数据?

这里是一些我正在缓存一些东西的代码示例。

import pandas as pd
from cacheout import Cache
cache=Cache(10,1000)

@cache.memoize()
def function1():
    df=pd.DataFrame('one':range(5),'two':range(5,10))  #just a little data, doesn't matter what
    print('iran')
    # return df.to_csv(index=False)
    return df

# @cached(cache)
@cache.memoize()
def function2(df):
    # df = pd.read_csv(StringIO(df))
    var1=df['one']
    var2=df['two']
    print('iran2')
    return var1, var2

def function3():
    df=function1()
    var1,var2=function2(df)
    
    print('this is var1[0]: '+str(var1[0]))
    print('this is var2[0]: '+str(var2[0]))
    
function3()

Cacheout 来了。 https://cacheout.readthedocs.io/en/latest/

【问题讨论】:

也许它将它保存在某个内部对象中,并且它没有官方功能来访问这些值。您必须检查源代码以了解如何获取它。 【参考方案1】:

正如@furas 提到的,我能够在源代码中找到一些东西。有一个字典生成函数是cacheout.Cache() 的方法,称为expire_times()。时间以 epoc 时间给出,因此这里有一个示例,将过期时间分配给以本地时间格式化的变量。

from cacheout import Cache
import datetime as dt
cache = Cache(maxsize=10, ttl=60)
...
#Code to cache stuff
...


cache_expire=dt.datetime.fromtimestamp(list(cache.expire_times().values())[0])

注意:在这种情况下,我只是得到了字典中第一件事的过期时间,但如果这也很重要,您可以访问缓存变量的名称。

另外,这是在文档中,但我只能在 pdf 版本中找到它

https://cacheout.readthedocs.io/_/downloads/en/latest/pdf/

【讨论】:

以上是关于从python中cacheout模块的Cache()方法获取数据缓存的时间的主要内容,如果未能解决你的问题,请参考以下文章

AttributeError:“模块”对象没有属性“lru_cache”

Nginx模块fastcgi_cache的几个注意点 转

python的functools模块

HTTP缓存与header模块

无法使用 XAMPP 从 Python cgi 脚本写入 PYTHON_EGG_CACHE

Django 缓存 Cache