Initial commit
This commit is contained in:
45
storage.py
Normal file
45
storage.py
Normal file
@@ -0,0 +1,45 @@
|
||||
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
|
||||
Reference in New Issue
Block a user