Miki Tebeka committed 8bf25a9

Update counter in transaction

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):
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.