]> khamidou — GitHub mirrors - kite.git/commitdiff
class to abstract json file loading
authorkarim hamidou <khamidou@gmail.com>
Sat, 23 Nov 2013 18:48:51 +0000 (19:48 +0100)
committerkarim hamidou <khamidou@gmail.com>
Sat, 23 Nov 2013 18:48:51 +0000 (19:48 +0100)
src/back/kite/jsonfile.py [new file with mode: 0644]

diff --git a/src/back/kite/jsonfile.py b/src/back/kite/jsonfile.py
new file mode 100644 (file)
index 0000000..22d0c3c
--- /dev/null
@@ -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()
+