json handling with autobackup and restore

This commit is contained in:
Ayush Saini 2022-05-05 23:07:56 +05:30
parent 5bd321c59c
commit 81d4344f62

View file

@ -62,11 +62,17 @@ def get_profiles() -> dict:
profiles of the players profiles of the players
""" """
if CacheData.profiles=={}: if CacheData.profiles=={}:
f=open(PLAYERS_DATA_PATH + "profiles.json","r") try:
profiles = json.load(f) f=open(PLAYERS_DATA_PATH + "profiles.json","r")
CacheData.profiles=profiles profiles = json.load(f)
f.close() CacheData.profiles=profiles
return profiles f.close()
except:
f=open(PLAYERS_DATA_PATH + "profiles.json.backup","r")
profiles = json.load(f)
CacheData.profiles=profiles
f.close()
return profiles
else: else:
return CacheData.profiles return CacheData.profiles
@ -273,11 +279,16 @@ def get_roles() -> dict:
roles roles
""" """
if CacheData.roles == {}: if CacheData.roles == {}:
f = open(PLAYERS_DATA_PATH + "roles.json", "r") try:
roles = json.load(f) f = open(PLAYERS_DATA_PATH + "roles.json", "r")
f.close() roles = json.load(f)
CacheData.roles = roles f.close()
return roles CacheData.roles = roles
except:
f = open(PLAYERS_DATA_PATH + "roles.json.backup", "r")
roles = json.load(f)
f.close()
CacheData.roles = roles
return CacheData.roles return CacheData.roles
@ -455,11 +466,16 @@ def get_custom() -> dict:
custom effects custom effects
""" """
if CacheData.custom == {}: if CacheData.custom == {}:
f=open(PLAYERS_DATA_PATH + "custom.json","r") try:
custom = json.load(f) f=open(PLAYERS_DATA_PATH + "custom.json","r")
f.close() custom = json.load(f)
CacheData.custom=custom f.close()
return custom CacheData.custom=custom
except:
f=open(PLAYERS_DATA_PATH + "custom.json.backup","r")
custom = json.load(f)
f.close()
CacheData.custom=custom
return CacheData.custom return CacheData.custom
@ -557,14 +573,18 @@ def load_cache():
get_custom() get_custom()
get_roles() get_roles()
import shutil
def dump_cache(): def dump_cache():
if CacheData.profiles!={}: if CacheData.profiles!={}:
shutil.copyfile(PLAYERS_DATA_PATH + "profiles.json",PLAYERS_DATA_PATH + "profiles.json.backup")
with open(PLAYERS_DATA_PATH + "profiles.json","w") as f: with open(PLAYERS_DATA_PATH + "profiles.json","w") as f:
json.dump(CacheData.profiles,f,indent=4) json.dump(CacheData.profiles,f,indent=4)
if CacheData.roles!={}: if CacheData.roles!={}:
shutil.copyfile(PLAYERS_DATA_PATH + "roles.json",PLAYERS_DATA_PATH + "roles.json.backup")
with open(PLAYERS_DATA_PATH + "roles.json", "w") as f: with open(PLAYERS_DATA_PATH + "roles.json", "w") as f:
json.dump(CacheData.roles, f, indent=4) json.dump(CacheData.roles, f, indent=4)
if CacheData.custom!={}: if CacheData.custom!={}:
shutil.copyfile(PLAYERS_DATA_PATH + "custom.json",PLAYERS_DATA_PATH + "custom.json.backup")
with open(PLAYERS_DATA_PATH + "custom.json", "w") as f: with open(PLAYERS_DATA_PATH + "custom.json", "w") as f:
json.dump(CacheData.custom, f, indent=4) json.dump(CacheData.custom, f, indent=4)
time.sleep(20) time.sleep(20)