Grandma_Baking_Book / template_manager.py
SissiFeng's picture
Upload 6 files
40fa48f verified
import json
from typing import List, Dict
from recipe_manager import Recipe
TEMPLATES_FILE = "templates.json"
def load_templates() -> List[Recipe]:
"""Load all recipe templates from the JSON file."""
try:
with open(TEMPLATES_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
return [Recipe.from_dict(item) for item in data]
except (FileNotFoundError, json.JSONDecodeError):
return []
def save_templates(templates: List[Recipe]):
"""Save all recipe templates to the JSON file."""
with open(TEMPLATES_FILE, "w", encoding="utf-8") as f:
json.dump([t.to_dict() for t in templates], f, ensure_ascii=False, indent=2)
def add_template(template: Recipe):
"""Add a new recipe template and save."""
templates = load_templates()
templates.append(template)
save_templates(templates)
def search_templates(keyword: str) -> List[Recipe]:
"""Search templates by keyword in name or category."""
templates = load_templates()
return [t for t in templates if keyword.lower() in t.name.lower() or keyword.lower() in t.category.lower()]
def list_templates() -> List[Recipe]:
"""List all recipe templates."""
return load_templates()