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

How to exclude parameters when caching function calls with DiskCache and memoize?

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


from diskcache import Cache
cache = Cache("database_cache)

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

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

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

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

您可以尝试编写自己的装饰器 - 使用 source code

或者在 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