好了,伙计们,让我举例说明,我有这个
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不是问题
提前谢谢
lru_cache(maxsize=None)
听起来是这样做的正确方法;通过关闭LRU机器,maxsize=None
使速度更快另一种方法是在程序开始时调用
get_config_file()
(在__init__
、get
,或者在实例化类的地方),将其分配给每个Scraper类上的一个属性,然后始终引用self.config
(或任何内容)。这样做的好处是,您可以跳过单元测试中的配置文件读取,您可以将测试配置直接传递到类中在这种情况下,由于类已经有一个
self.conf
,因此最好使用文件中的值更新该字典,而不是引用每个方法中的两个位置我完全忘记了
@functools.cached_property
相关问题 更多 >
编程相关推荐