0ptr/store.py

69 lines
1.6 KiB
Python
Raw Normal View History

2023-06-09 11:19:47 +00:00
from models.base import Base
from models.waypoint import Waypoint
from models.sector import Sector
from models.system import System
2023-06-10 17:39:32 +00:00
from models.agent import Agent
2023-06-09 20:20:46 +00:00
from os.path import isfile, dirname, isdir
import os
import json
2023-06-09 11:19:47 +00:00
class Store:
2023-06-09 20:20:46 +00:00
def __init__(self, data_dir):
self.data_dir = data_dir
self.data = {}
def path(self, obj):
return os.path.join(self.data_dir, obj.path())
def load(self, obj):
path = self.path(obj)
if not isfile(path):
return obj
with open(path) as f:
data = json.load(f)
data['store'] = self
2023-06-10 17:39:32 +00:00
data['dirty'] = False
2023-06-09 20:20:46 +00:00
obj.__dict__ = data
2023-06-09 20:20:46 +00:00
def store(self, obj):
path = self.path(obj)
path_dir = dirname(path)
data = obj.dict()
if not isdir(path_dir):
os.makedirs(path_dir, exist_ok=True)
with open(path, 'w') as f:
json.dump(data, f, indent=2)
obj.dirty = False
def get(self, typ, symbol):
obj = typ(symbol, self)
self.load(obj)
self.data[symbol] = obj
return obj
2023-06-10 17:39:32 +00:00
def all(self, path, typ):
if hasattr(path, 'path'):
path = path.path()
path = os.path.join(self.data_dir, path)
if not isdir(path):
return
ext = '.' + typ.ext()
for f in os.listdir(path):
fil = os.path.join(path, f)
if not isfile(fil):
continue
if not fil.endswith(ext):
continue
symbol = f[:-len(ext)]
yield self.get(typ, symbol)
2023-06-09 20:20:46 +00:00
def flush(self):
for obj in self.data.values():
2023-06-10 17:39:32 +00:00
if obj.dirty:
self.store(obj)
2023-06-09 20:20:46 +00:00
def foo(self):
2023-06-09 20:20:46 +00:00
s = self.get(System, 'dez-hq14')
print(s)