From: karim hamidou Date: Sat, 23 Nov 2013 18:48:51 +0000 (+0100) Subject: class to abstract json file loading X-Git-Url: http://git.khamidou.com/?a=commitdiff_plain;h=d493a43c04c631060b97f42a3ee913240b80f28a;p=kite.git class to abstract json file loading --- diff --git a/src/back/kite/jsonfile.py b/src/back/kite/jsonfile.py new file mode 100644 index 0000000..22d0c3c --- /dev/null +++ b/src/back/kite/jsonfile.py @@ -0,0 +1,34 @@ +# serialize and deserialize to json. +# reading and writing is locking +import os +import json +from lockfile import FileLock + +class JsonFile(object): + def __init__(self, path=None): + self.path = path + self.data = None + self.refresh() + + def refresh(self): + if self.path != None: + try: + with FileLock(self.path): + fd = open(self.path, "r") + self.data = json.load(fd) + fd.close() + except IOError: + pass + + def save(self): + def save_proper(): + with open(self.path, "w+") as fd: + json.dump(self.data, fd) + + # Lock the file only if it already exists + if os.path.exists(self.path): + with FileLock(self.path): + save_proper() + else: + save_proper() +