在python中缓存非更改的频繁读取文件

2024-05-19 21:14:11 发布

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

好了,伙计们,让我举例说明,我有这个

def get_config_file(file='scrapers_conf.json'):
    """
    Load the default .json config file
    """
    return json.load(open(file))

这个函数调用很多,它将在一个服务器上,每个请求都会触发这个函数至少5次,我已经运行了多个scraper,每个scraper的形状如下

为了方便起见,我删除了helper方法,问题是,每个scraper都应该有自己的请求头、负载等等。。。或者使用位于scrapers_conf.json的默认值

class Scraper(threading.Thread): # init is overriden and has set .conf
    def run(self):
        self.get()

    def get(self):
        # logic

问题是我得到的标题是

class Scraper(threading.Thread):
    def run(self):
        self.get()

    def get(self):
        headers = self.conf.get('headers') or get_config_file().get('headers')

如您所见,每个请求上的每个实例都会调用get_config_file()函数,我认为这在我的情况下不是最优的。我知道lru_cache,但我认为这不是最佳解决方案(请纠正我!)

配置文件很小,os.sys.getsizeof报告小于1KB

我想把它留着,因为我认为读1KB不是问题

提前谢谢


Tags: 函数selfconfigjsongetconfdefscraper
2条回答

lru_cache(maxsize=None)听起来是这样做的正确方法;通过关闭LRU机器,maxsize=None使速度更快

另一种方法是在程序开始时调用get_config_file()(在__init__get,或者在实例化类的地方),将其分配给每个Scraper类上的一个属性,然后始终引用self.config(或任何内容)。这样做的好处是,您可以跳过单元测试中的配置文件读取,您可以将测试配置直接传递到类中

在这种情况下,由于类已经有一个self.conf,因此最好使用文件中的值更新该字典,而不是引用每个方法中的两个位置

我完全忘记了@functools.cached_property

@cached_property
def get_config_file(file='scrapers_conf.json'):
    """
    Load the default .json config file
    """
    return json.load(open(file))

相关问题 更多 >