
Project
Capstone 2: Saving the Network
A tracker that forgets everything on restart isn't much use. The storage layer saves tasks to a JSON file and loads them back.
Keep storage separate from the model and the commands. Then you could later swap JSON for a database without touching the rest of the app.
path.write_text(json.dumps(data, indent=2))
data = json.loads(path.read_text())
Two details that real apps get right:
- A missing file is not an error on the very first run. It just means "no tasks yet".
- IDs keep counting after a reload.
addalready usesmax(existing ids) + 1, so that works as long asloadrestores the real ids.
Assignment
Task (from last lesson), __init__ and add are done. Write:
complete(task_id): mark the task as done and return it. If the id is unknown, raiseKeyError(f"no task #{task_id}").save(): write a JSON list of task dicts toself.path.- The classmethod
load(path): return a store with the tasks from the file, or an empty store if the file doesn't exist.
Task (from last lesson), __init__ and add are done. Write:
complete(task_id): mark the task as done and return it. If the id is unknown, raiseKeyError(f"no task #{task_id}").save(): write a JSON list of task dicts toself.path.- The classmethod
load(path): return a store with the tasks from the file, or an empty store if the file doesn't exist.
main.py Python sleeping
Press Run to try your code, then Check to test it.