[docs]classJsonManager:''' :param main_dir: The main directory to write ``json files``. :type main_dir: :obj:`str` or :obj:`None` :param base_dict: The base dict for ``json files``. :type base_dict: :obj:`dict` :param debug: Pass :obj:`True` to see more information in ``STDOUT``. :type debug: :obj:`bool`, optional '''def__init__(self,main_dir:Optional[str],base_dict:dict[str,Any],debug:Optional[bool]=None):ifnotisinstance(main_dir,(str,type(None))):raiseTypeError("'main_dir' must be str, pass None"' to use the current directory.')ifmain_dirisnotNoneandnotos.path.isdir(main_dir):raiseNotADirectoryError("'main_dir' is not a directory, pass"' None to use the current one.')ifnotisinstance(base_dict,dict):raiseTypeError("'base_dict' must be dict,"f' got {base_dict.__class__.__name__}.')ifmain_dirisNone:main_dir='./'elifnotmain_dir.endswith('/'):main_dir+='/'self._main_dir=main_dirself._updates={}self._base_dict=base_dictself._debug=debugifdebug:logger.setLevel(10)@propertydefmain_dir(self)->str:returnself._main_dir@propertydefupdates(self)->dict[int,dict[str,Any]]:returnself._updates@propertydefbase_dict(self)->dict[str,Any]:returnself._base_dict.copy()
[docs]defget(self,chat_id:int,/)->dict[str,Any]:iftype(chat_id)isnotint:raiseTypeError("'chat_id' must be int in JsonManager.get()"f" method, got {chat_id.__class__.__name__}.")ifchat_idinself.updates:ifself._debug:logger.debug(f'Got {chat_id} from updates.')else:file_name=_json_format(chat_id)try:withopen(self.main_dir+file_name)asr:self.updates[chat_id]=json.loads(r.read())exceptFileNotFoundError:raiseFileNotFoundError(f'No such file {self.main_dir+file_name!r}.'' You should use the JsonManager.check() method'' before to call the JsonManager.get() to ensure the file exists.')ifself._debug:logger.debug(f'Got {chat_id} from file.')returnself.updates[chat_id]
[docs]defmerge(self)->dict[int,dict[str,Any]]:forfile_nameinos.listdir(self.main_dir):ifre.match(r'^(\-|\d){0,1}\d+\.json$',file_name):chat_id=file_name.replace('.json',str())self.get(int(chat_id))else:logger.warning(f'Unexpected file {self.main_dir+file_name!r}'' in the JsonManager.merge() method, it was skipped.')returnself.updates