Commits

Miki Tebeka committed 8bf25a9

Update counter in transaction

  • Participants
  • Parent commits cfeeeb9
  • Branches counter-txn

Comments (0)

Files changed (1)

 
     count = db.IntegerProperty(default=0)
 
+def get_counter():
+    '''Get global counter object, create one first time.'''
+    counter = Counter.get_by_key_name(Counter.key_name)
+    if counter is None:
+        counter = Counter(key_name=Counter.key_name)
+    return counter
+
 def record_hit():
     '''Record a page hit, increment counter and return count.'''
-    counter = Counter.get_or_insert(Counter.key_name)
-    counter.count += 1
-    counter.put()
-    return counter.count
+
+    # Sadly, Python does not have proper lexical scoping. This is a hack round
+    # it.
+    count = [0]
+
+    # Update count in transaction
+    def txn():
+        counter = get_counter()
+        counter.count += 1
+        counter.put()
+        count[0] = counter.count
+
+    db.run_in_transaction(txn)
+
+    return count[0]
 
 
 class Home(webapp.RequestHandler):