Skip to content

Instantly share code, notes, and snippets.

@dound
Created February 10, 2012 00:52
Show Gist options
  • Save dound/1784891 to your computer and use it in GitHub Desktop.
Save dound/1784891 to your computer and use it in GitHub Desktop.
A simple, high accuracy counter (not appropriate for higher frequency usage [>1 update/sec for any key])
from google.appengine.ext import db
class Counter(db.Model):
"""Persistent storage of a counter's values"""
# key_name is the counter's name
value = db.IntegerProperty(indexed=False)
@classmethod
def get(cls, name):
"""Returns the value of the specified counter"""
counter = cls.get_by_key_name(name)
if not counter:
return 0
return counter.value
@classmethod
def incr(cls, name, delta=1):
"""Increments a counter"""
def tx():
counter = cls.get_by_key_name(name)
if not counter:
counter = Counter(key_name=name, value=0)
counter.value += delta
counter.put()
db.run_in_transaction(tx)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment