You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Python cacheout模块的Cache()方法中获取缓存创建及过期时间

解答

可以获取缓存的创建时间与到期时间,cacheout未在公开文档中明确标注相关API,但其内部存储了完整的缓存元数据,可通过内部属性读取。

实现原理

cacheout的Cache实例会将所有缓存条目存储在私有属性__items中,每个条目为CacheItem类实例,自带以下属性:

  • created:缓存创建时的时间戳(单位:秒)
  • expires:缓存到期的时间戳(单位:秒)
  • ttl:缓存剩余存活时长(单位:秒)

具体使用方法

1. 读取普通缓存键的元数据

from cacheout import Cache
import time

cache = Cache(maxsize=10, ttl=1000)
# 写入一个普通缓存
cache.set('test_key', 'test_value')

# 获取缓存条目
item = cache._Cache__items.get('test_key')
if item:
    print(f"创建时间:{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(item.created))}")
    print(f"到期时间:{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(item.expires))}")
    print(f"剩余存活时间:{item.ttl}秒")

2. 读取memoize装饰函数的缓存元数据

你示例中使用了memoize装饰器,它生成的缓存键会自动包含函数名与参数哈希,你可以通过memoize装饰器返回的对象的make_key方法生成对应参数的缓存键,再读取元数据:

import pandas as pd
import time
from cacheout import Cache

cache = Cache(10, 1000)

@cache.memoize()
def function1():
    df=pd.DataFrame({'one':range(5),'two':range(5,10)})
    print('iran')
    return df

@cache.memoize()
def function2(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]))
    
    # 读取function1无参调用的缓存元数据
    func1_key = function1.make_key()
    func1_item = cache._Cache__items.get(func1_key)
    if func1_item:
        print(f"function1缓存创建时间:{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(func1_item.created))}")
        print(f"function1缓存到期时间:{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(func1_item.expires))}")
    
    # 读取function2传入当前df的缓存元数据
    func2_key = function2.make_key(df)
    func2_item = cache._Cache__items.get(func2_key)
    if func2_item:
        print(f"function2缓存创建时间:{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(func2_item.created))}")
        print(f"function2缓存到期时间:{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(func2_item.expires))}")

function3()

注意事项

  • 读取私有属性属于非公开API用法,版本升级时可能存在兼容性变动
  • memoize装饰器的键生成依赖参数哈希,如果参数是不可哈希的对象(比如未自定义哈希方法的自定义类实例),会无法生成有效缓存键,你示例中传入DataFrame作为参数可以正常工作是因为cacheout对常用对象做了哈希兼容处理。

内容的提问来源于stack exchange,提问作者bart cubrich

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 19:54:04