如何在使用DiskCache和memoize缓存函数调用时排除参数?

2024-10-02 06:26:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python的DiskCache和memoize装饰器来缓存对静态数据数据库的函数调用


from diskcache import Cache
cache = Cache("database_cache)

@cache.memoize()
def fetch_document(row_id: int, user: str, password: str):
    ...

我不希望用户和密码成为缓存密钥的一部分

如何从密钥生成中排除参数


Tags: fromimport数据库cachedef密钥装饰database
1条回答
网友
1楼 · 发布于 2024-10-02 06:26:34

memoize的文档没有显示排除参数的选项

您可以尝试使用source code编写自己的decorator

或者在fetch_document内部自己使用cache-类似这样的东西

def fetch_document(row_id: int, user: str, password: str):
    if row_id in cache:
         return cache[row_id]

    # ... code ...
              
    # result = ...

    cache[row_id] = result

    return result              

编辑:

或者创建函数的缓存版本-如下所示

def cached_fetch_document(row_id: int, user: str, password: str):
    if row_id in cache:
         return cache[row_id]

    result = fetch_document(row_id: int, user: str, password: str)

    cache[row_id] = result

    return result              

然后,您可以决定是否使用cached_fetch_document代替fetch_document

相关问题 更多 >

    热门问题