Python通用缓存d

2024-04-27 04:05:10 发布

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

我的脚本中有以下装饰程序:

def cached_to_disk(func):
    """Save the results of the func to the directory specified in datadir."""
    path = datadir + func.__name__
    if not os.path.exists(path):
        os.makedirs(path)

    @wraps(func)
    def cached_func(page):
        fullpath = "{}/{}".format(path, page.url)
        if os.path.isfile(fullpath):
            with open(fullpath) as cached_file:
                data = cached_file.read()
        else:
            data = func(page)
            if data is not None:
                with open(fullpath, "w") as cached_file:
                    cached_file.write(data)
        return data
    return cached_func

效果很好。但是,我现在想将它扩展到任何函数。有点像这样:

@wraps(func)
def cached_func(*args, **kwargs):
    pass

我的问题是确定在哪里保存缓存。当我使用自定义页面对象时,我可以使用(规范化的)url作为文件名。但是,当func可以接收任意参数时,如何确定文件名就不那么清楚了。我曾考虑过使用args[0].__repr__,但对于有多个参数(例如download(site, page_on_the_site)之类)或没有任何参数的函数来说,这听起来不是个好主意。你知道吗

理想情况下,我希望通用装饰器对于它已经支持的那些函数保持完全相同的工作方式。你知道吗

有没有一个简单而健壮的方法来做这样的事情?你知道吗


Tags: thetopath函数data参数ifos
1条回答
网友
1楼 · 发布于 2024-04-27 04:05:10

没有一个简单的解决方案适用于任何类型的争论。您需要以某种方式序列化参数,并且并非所有参数都可以序列化(例如,闭包通常很棘手)。在^{}模块中可以找到一些接近的东西。你知道吗

它基本上为您提供了一个类似字典的对象,任何可以pickle的对象都可以用作键,因此您可以使用(func.__name__, args, kwargs)之类的东西。你知道吗

注意,这比使用Python字典更通用,因为Python字典要求键是可散列的。你知道吗

相关问题 更多 >