niming_backend/utils/setting_loader.py

32 lines
878 B
Python
Raw Permalink 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-12-12 11:30:51 +08:00
# 如果是list: 檢查內容
if PLATFORM_SETTING_MODEL.get(name)[0] == list:
2024-11-18 02:47:25 +08:00
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-12-12 11:30:51 +08:00
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