Files
ewoooc/services/json_storage.py
ooo c91dc273f0
All checks were successful
CD Pipeline / deploy (push) Successful in 1m9s
refactor(p1-01f): JSON 持久化抽到 services/json_storage.py
- load_categories / save_categories / load_scheduler_stats 三個函數搬出
- CATEGORIES_JSON_PATH / SCHEDULER_STATS_PATH 常數同步搬移
- app.py 改 import 維持原呼叫路徑

行數變化: app.py 7,070 → 7,053 (-17)
2026-04-28 19:42:05 +08:00

38 lines
1.2 KiB
Python

"""JSON 檔案儲存:分類設定、排程統計等小型持久化資料。
從 app.py 抽出。每個函數對應一個 JSON 檔案。
"""
import json
import os
from config import BASE_DIR
CATEGORIES_JSON_PATH = os.path.join(BASE_DIR, 'data', 'categories.json')
SCHEDULER_STATS_PATH = os.path.join(BASE_DIR, 'data', 'scheduler_stats.json')
def load_categories():
"""從 JSON 檔案載入分類列表(檔案不存在或損毀回傳 [])。"""
try:
with open(CATEGORIES_JSON_PATH, 'r', encoding='utf-8') as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
return []
def save_categories(categories):
"""將分類列表儲存到 JSON 檔案。"""
with open(CATEGORIES_JSON_PATH, 'w', encoding='utf-8') as f:
json.dump(categories, f, ensure_ascii=False, indent=4)
def load_scheduler_stats():
"""讀取排程統計資料(檔案不存在或損毀回傳 {})。"""
if os.path.exists(SCHEDULER_STATS_PATH):
try:
with open(SCHEDULER_STATS_PATH, 'r', encoding='utf-8') as f:
return json.load(f)
except (IOError, json.JSONDecodeError):
return {}
return {}