Files
tt/lib/DataStore.py

41 lines
1.3 KiB
Python
Raw Normal View History

2024-06-13 10:10:34 +02:00
from pathlib import Path
from .TimeSlot import TimeSlot
import json
class DataStore:
def __init__(self, filename: Path, create=False):
self._filename = filename
if create:
2024-06-13 10:21:19 +02:00
# Store emtpty list
2024-06-13 10:10:34 +02:00
self._time_slots = []
2024-06-13 11:15:48 +02:00
self.write_update()
2024-06-13 10:10:34 +02:00
else:
2024-06-13 10:21:19 +02:00
# Load dicts from file
2024-06-13 10:10:34 +02:00
with open(self._filename, "r") as f:
self._time_slots = list(json.load(f))
2024-06-13 10:21:19 +02:00
# Convert dicts into TimeSlot objects
def deserialize(d: dict) -> TimeSlot:
ts = TimeSlot.__new__(TimeSlot) # Create a new, empty instance
ts.__dict__.update(d)
return ts
self._time_slots = [deserialize(d) for d in self._time_slots]
2024-06-13 11:15:48 +02:00
def write_update(self):
2024-06-13 10:21:19 +02:00
"""Saves the updates made to the DataStore object to disk."""
2024-06-13 10:10:34 +02:00
with open(self._filename, "w+") as f:
json.dump(self._time_slots, f, default=vars)
def add_time_slot(self, time_slot: TimeSlot):
self._time_slots.append(time_slot)
2024-06-13 11:15:48 +02:00
self.write_update()
2024-06-13 10:10:34 +02:00
def remove_time_slot(self, time_slot: TimeSlot):
self._time_slots.remove(time_slot)
2024-06-13 11:15:48 +02:00
self.write_update()
2024-06-13 10:10:34 +02:00
def get_all_time_slots(self):
return self._time_slots[:]