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

Python 如何在使用DiskCache和memoize缓存函数调用时排除参数?,python,diskcache,Python,Diskcache,我使用Python的DiskCache和memoize装饰器来缓存对静态数据数据库的函数调用 从diskcache导入缓存 cache=cache(“数据库\缓存”) @cache.memoize() def fetch_文档(行id:int,用户:str,密码:str): ... 我不希望用户和密码成为缓存密钥的一部分 如何从密钥生成中排除参数?的文档未显示排除参数的选项 您可以尝试编写自己的decorator-using 或者在fetch\u document中自己使用cache——类似

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


从diskcache导入缓存
cache=cache(“数据库\缓存”)
@cache.memoize()
def fetch_文档(行id:int,用户:str,密码:str):
...
我不希望用户和密码成为缓存密钥的一部分

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

的文档未显示排除参数的选项

您可以尝试编写自己的decorator-using

或者在
fetch\u 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              

编辑:

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

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              

然后,您可以根据文档决定是否要使用
缓存的\u fetch\u文档
代替
获取文档

,因为您不能排除参数。您必须编写自己的decorator。或者在
获取文档
内部使用
缓存[row\u id]=result
与'if/elseI不知道我可以直接与缓存对话。我想我必须使用一个装饰器。这使生活变得更容易。我可以将
缓存
视为存储在文件中的字典。似乎像
这样的参数过期
,我通常传递给装饰器
@cache.memoize
可以通过th
cach.set(过期)