02 Intermediate Python: OOP, Types, Errors & Testing/2.14 Lab code (reference solutions)/2.14.4 lab/library/storage.py
§ 2.14.4section 18 of 20·~5 min
lab/library/storage.py
import json
from dataclasses import asdict
from pathlib import Path
from library.library import Library
from library.models import Book, Member
def save(library: Library, path: Path) -> None:
data = {
"books": [asdict(b) for b in library.books.values()],
"members": [asdict(m) for m in library.members.values()],
}
path.write_text(json.dumps(data, indent=2, ensure_ascii=False))
def load(path: Path) -> Library:
data = json.loads(path.read_text())
library = Library()
for b in data["books"]:
library.add_book(Book(**b))
for m in data["members"]:
library.add_member(Member(**m))
return library