Created
February 10, 2012 00:52
-
-
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])
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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