Store setup

This commit is contained in:
Richard Bronkhorst 2023-06-09 22:20:46 +02:00
parent d4c593208a
commit eeb063f307
5 changed files with 60 additions and 6 deletions

View File

@ -43,7 +43,6 @@ class CommandLine:
print('byebye!')
self.stopping = True
def do_reload(self):
self.reloading = True

View File

@ -10,7 +10,14 @@ class Commander(CommandLine):
def do_foo(self):
self.store.foo()
self.store.flush()
def main(args):
c = Commander(args.store_dir)
c.run()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--store-dir', default='data')
args = parser.parse_args()
main(args)

View File

@ -1,9 +1,18 @@
from copy import deepcopy
class Base:
symbol: str
def __init__(self, symbol, store):
self.symbol = symbol
self.store = store
self.dirty = True
def dict(self):
r = deepcopy(self.__dict__)
del r['store']
del r['dirty']
return r
def path(self):
raise NotImplementedError('path')

View File

@ -5,3 +5,7 @@ from .base import Base
class System(Base):
def ext(self):
return 'stm'
def path(self):
sector, symbol = self.symbol.split('-')
return f'atlas/{sector}/{symbol}.{self.ext()}'

View File

@ -3,12 +3,47 @@ from models.waypoint import Waypoint
from models.sector import Sector
from models.system import System
from models.setting import Setting
from os.path import isfile, dirname, isdir
import os
import json
class Store:
def __init__(self, fil):
pass
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
obj.__dict__ = data
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
def flush(self):
for obj in self.data.values():
self.store(obj)
def foo(self):
w = Waypoint('jdjdj', self)
print(w.__dict__)
s = self.get(System, 'dez-hq14')
print(s)