niming_backend/utils/setting_loader.py

40 lines
1.0 KiB
Python
Raw Normal View History

2024-11-14 13:03:00 +08:00
import json
2024-11-19 21:22:01 +08:00
from utils.platform_consts import PLATFORM_SETTING_MODEL
2024-11-14 13:03:00 +08:00
def loadset():
with open("./settings.json", "r", encoding = "utf-8") as f:
d = json.load(f)
2024-11-18 02:47:25 +08:00
return d
def typechecker(name:str, value):
2024-11-19 21:22:01 +08:00
# 型別驗證
if not(name in PLATFORM_SETTING_MODEL.keys()) or not(isinstance(value, PLATFORM_SETTING_MODEL.get(name)[0])):
2024-11-18 02:47:25 +08:00
return 0
2024-11-19 21:22:01 +08:00
# 確定是否是可迭代物件
2024-11-18 02:47:25 +08:00
iterable = False
try:
2024-11-19 21:22:01 +08:00
iter(PLATFORM_SETTING_MODEL.get(name)[0])
2024-11-18 02:47:25 +08:00
iterable = True
except:
iterable = False
2024-11-19 21:22:01 +08:00
# 如果可迭代,就把裡面每個元素都檢查型別
2024-11-18 02:47:25 +08:00
if iterable:
for v in value:
2024-11-19 21:22:01 +08:00
if not(isinstance(v, PLATFORM_SETTING_MODEL.get(name)[1])): return 0
2024-11-18 02:47:25 +08:00
return 1
def writeset(name:str, value):
2024-11-19 21:22:01 +08:00
# 驗證寫入資料型別
2024-11-18 02:47:25 +08:00
if not typechecker(name, value): return 0
2024-11-19 21:22:01 +08:00
# 寫入
2024-11-18 02:47:25 +08:00
d:dict = loadset()
d[name] = value
with open("./settings.json", "w", encoding = "utf-8") as f:
json.dump(d, f, ensure_ascii=False)
2024-11-14 13:03:00 +08:00
return d