Dump feeds database to tempfile before overwriting
authorJack Miller <jack@codezen.org>
Sun, 29 Nov 2015 01:46:57 +0000 (19:46 -0600)
committerJack Miller <jack@codezen.org>
Sun, 29 Nov 2015 01:46:57 +0000 (19:46 -0600)
canto_next/storage.py

index c6de8a4..bdc632f 100644 (file)
@@ -10,7 +10,9 @@
 from .feed import wlock_feeds
 from .hooks import call_hook
 
+import tempfile
 import logging
+import shutil
 import json
 import gzip
 import time
@@ -111,9 +113,17 @@ class CantoShelf():
         if self.cache == {}:
             return
 
-        fp = gzip.open(self.filename, "wt", 9, "UTF-8")
+        f, tmpname = tempfile.mkstemp(None, "feeds", os.path.dirname(self.filename))
+        os.close(f)
+
+        fp = gzip.open(tmpname, "wt", 9, "UTF-8")
         json.dump(self.cache, fp, indent=4, sort_keys=True)
         fp.close()
+
+        log.debug("Written tempfile.")
+
+        shutil.move(tmpname, self.filename)
+
         log.debug("Synced.")
 
     def close(self):