46 lines
1.0 KiB
Python
46 lines
1.0 KiB
Python
import os
|
|
import pickle
|
|
import uuid
|
|
import time
|
|
|
|
class Storage():
|
|
objects = {}
|
|
|
|
def __init__(self, name):
|
|
self.name = f"./{name}.obj"
|
|
self._load()
|
|
|
|
def _load(self):
|
|
if not os.path.exists(self.name):
|
|
self._save()
|
|
|
|
with open(self.name, "rb") as s:
|
|
self.objects = pickle.load(s)
|
|
|
|
def _save(self):
|
|
with open(self.name, "wb") as s:
|
|
pickle.dump(self.objects, s, pickle.HIGHEST_PROTOCOL)
|
|
|
|
def create(self, obj):
|
|
obj["id"] = uuid.uuid1().hex
|
|
self.update(obj)
|
|
|
|
def read(self, ts = 0):
|
|
if ts == 0:
|
|
return self.objects
|
|
else:
|
|
return { k: v for k, v in self.objects.items() if v["ts"] > ts }
|
|
|
|
def update(self, obj):
|
|
obj["ts"] = time.time()
|
|
self.objects[obj["id"]] = obj
|
|
self._save()
|
|
|
|
def delete(self, obj_id):
|
|
if not obj_id in self.objects:
|
|
return False
|
|
|
|
del self.objects[obj_id]
|
|
self._save()
|
|
return True
|