[Python-checkins] r69309 - sandbox/trunk/dbm_sqlite/alt/dbdict.py

raymond.hettinger python-checkins at python.org
Thu Feb 5 18:07:33 CET 2009


Author: raymond.hettinger
Date: Thu Feb  5 18:07:33 2009
New Revision: 69309

Log:
Don't overwrite db until we know that serialization is successful.

Modified:
   sandbox/trunk/dbm_sqlite/alt/dbdict.py

Modified: sandbox/trunk/dbm_sqlite/alt/dbdict.py
==============================================================================
--- sandbox/trunk/dbm_sqlite/alt/dbdict.py	(original)
+++ sandbox/trunk/dbm_sqlite/alt/dbdict.py	Thu Feb  5 18:07:33 2009
@@ -10,7 +10,9 @@
 
 '''
 
-import os, pickle, json, csv
+import pickle, json, csv
+import os, shutil, warnings
+warnings.filterwarnings("ignore", message='tempnam')
 
 class DictDB(dict):
 
@@ -29,12 +31,17 @@
         self.update(*args, **kwds)
 
     def sync(self):
+        tempname = os.tempnam()
         if self.flag != 'r':
-            file = __builtins__.open(self.filename, 'wb')
+            file = __builtins__.open(tempname, 'wb')
+            success = False
             try:
                 self.dump(file)
+                success = True
             finally:
                 file.close()
+            if success:
+                shutil.move(tempname, self.filename)
             if self.mode:
                 os.chmod(self.filename, self.mode)
 
@@ -68,18 +75,19 @@
             raise NotImplementedError('Unknown format: %r' % self.format)
 
 
-def myopen(filename, flag='c', mode=0o666, format='csv'):
+def dbopen(filename, flag='c', mode=0o666, format='csv'):
     return DictDB(filename, flag, mode, format)
 
 
 
 if __name__ == '__main__':
+    import random
     os.chdir('/dbm_sqlite/alt')
     print(os.getcwd())
-    s = myopen('tmp.shl', 'c', format='json')
+    s = dbopen('tmp.shl', 'c', format='json')
     print(s, 'start')
-    s['xyz'] = 'pdq'
     s['abc'] = '123'
+    s['rand'] = random.randrange(10000)
     s.close()
     f = __builtins__.open('tmp.shl', 'rb')
     print (f.read())


More information about the Python-checkins mailing list