diff web/atomicfile.py @ 501:236e5d131b3e

Add url link, improve atomicfile
author Matt Johnston <matt@ucc.asn.au>
date Sun, 30 Mar 2014 20:20:30 +0800
parents 46e327c00246
children 87c20b8c5472
line wrap: on
line diff
--- a/web/atomicfile.py	Mon Mar 24 20:49:00 2014 +0800
+++ b/web/atomicfile.py	Sun Mar 30 20:20:30 2014 +0800
@@ -4,43 +4,44 @@
 import sys
 
 class AtomicFile(object):
-	DELAY = 0.5
-	def __init__(self, name):
-		self.name = name
+    DELAY = 0.5
+    def __init__(self, name):
+        self.name = name
 
-	def write(self, data, timeout = 5):
-		try:
-			end = time.time() + timeout
-			with open(self.name, "r+") as f:
-				while timeout == 0 or time.time() < end:
-					try:
-						fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
-					except IOError:
-						time.sleep(DELAY)
-						continue
+    def write(self, data, timeout = 5):
+        try:
+            end = time.time() + timeout
+            with open(self.name, "r+") as f:
+                while timeout == 0 or time.time() < end:
+                    try:
+                        fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
+                    except IOError:
+                        time.sleep(DELAY)
+                        continue
 
-					f.write(data)
-					return True
+                    os.ftruncate(f.fileno(), 0)
+                    f.write(data)
+                    return True
 
-		except IOError, e:
-			print>>sys.stderr, e
+        except IOError, e:
+            print>>sys.stderr, e
 
-		return False
+        return False
 
-	def read(self, timeout = 5):
-		try:
-			end = time.time() + timeout
-			with open(self.name, "r") as f:
-				while timeout == 0 or time.time() < end:
-					try:
-						fcntl.lockf(f, fcntl.LOCK_SH | fcntl.LOCK_NB)
-					except IOError:
-						time.sleep(DELAY)
-						continue
+    def read(self, timeout = 5):
+        try:
+            end = time.time() + timeout
+            with open(self.name, "r") as f:
+                while timeout == 0 or time.time() < end:
+                    try:
+                        fcntl.lockf(f, fcntl.LOCK_SH | fcntl.LOCK_NB)
+                    except IOError:
+                        time.sleep(DELAY)
+                        continue
 
-					return f.read()
+                    return f.read()
 
-		except IOError, e:
-			print>>sys.stderr, e
+        except IOError, e:
+            print>>sys.stderr, e
 
-		return None
+        return None