好吧,大家讓我舉例說明,我有這個def get_config_file(file='scrapers_conf.json'): """ Load the default .json config file """ return json.load(open(file))這個函數被調用很多,這將在服務器上,每個請求都會觸發這個函數至少 5 次,我有多個刮刀在運行,每個刮刀都在以下形狀上。為了方便起見,我刪除了輔助方法,問題是,每個抓取工具都應該有自己的請求標頭、有效負載……或者使用位于的默認標頭scrapers_conf.jsonclass 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報告不到 1 KB。我正在考慮將其保留,因為考慮到讀取 1 KB 不是問題。
2 回答

炎炎設計
TA貢獻1808條經驗 獲得超4個贊
我完全忘記了@functools.cached_property
@cached_property
def get_config_file(file='scrapers_conf.json'):
"""
Load the default .json config file
"""
return json.load(open(file))

夢里花落0921
TA貢獻1772條經驗 獲得超6個贊
lru_cache(maxsize=None)
聽起來是正確的方法;maxsize=None
通過關閉 LRU 機制可以使其速度更快。
另一種方法是get_config_file()
在程序的開頭(在__init__
、get
或實例化類的地方)調用,將其分配給每個 Scraper 類上的一個屬性,然后始終引用self.config
(或其他方式)。這樣做的優點是您可以在單元測試中跳過讀取配置文件 - 您可以將測試配置直接傳遞到類中。
在這種情況下,由于該類已經有一個self.conf
,因此最好使用文件中的值更新該字典,而不是在每個方法中引用兩個位置。
添加回答
舉報
0/150
提交
取消