Created
June 24, 2010 21:10
-
-
Save gjritter/451988 to your computer and use it in GitHub Desktop.
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 | |
from google.appengine.ext import webapp | |
from google.appengine.ext.webapp.util import run_wsgi_app | |
import random | |
class SimpleCounterShard(db.Model): | |
count = db.IntegerProperty(required=True, default=0) | |
NUM_SHARDS = 10 | |
def get_count(): | |
total = 0 | |
for counter in SimpleCounterShard.all(): | |
total += counter.count | |
return total | |
def increment(): | |
def txn(): | |
index = random.randint(0, NUM_SHARDS - 1) | |
shard_name = "shard" + str(index) | |
counter = SimpleCounterShard.get_by_key_name(shard_name) | |
if counter is None: | |
counter = SimpleCounterShard(key_name=shard_name) | |
counter.count += 1 | |
counter.put() | |
db.run_in_transaction(txn) | |
class IncrementPage(webapp.RequestHandler): | |
def get(self): | |
increment() | |
class CounterPage(webapp.RequestHandler): | |
def get(self): | |
self.response.out.write("Hello, %d!" % (get_count(), )) | |
class DeletePage(webapp.RequestHandler): | |
def get(self): | |
for counter in SimpleCounterShard.all(): | |
counter.delete() | |
application = webapp.WSGIApplication([('/', CounterPage), ('/inc/', IncrementPage), ('/delete/', DeletePage)]) | |
def main(): | |
run_wsgi_app(application) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment