# Path: counters/models.py
# class Shard(db.Model):
#     name = db.StringProperty(required=True)
#     count = db.IntegerProperty(required=True, default=0)
# 
# class Config(db.Model):
#     name = db.StringProperty(required=True)
#     num_shards = db.IntegerProperty(required=True, default=20)


import random
from google.appengine.ext import db
from google.appengine.api import memcache
from counters.models import Shard, Config
        for counter in Shard.all().filter('name = ', name):
            total += counter.count
        memcache.add(name, str(total), 60)
    return total


def increment(name, delta=1):
    """
    Increment the value for a given sharded counter.
    """
    config = Config.get_or_insert(name, name=name)

    def txn():
        index = random.randint(1, config.num_shards)
        shard_name = name + str(index)
        counter = Shard.get_by_key_name(shard_name)
        if counter is None:
            counter = Shard(key_name=shard_name, name=name)
        counter.count += delta
        counter.put()

    db.run_in_transaction(txn)
    memcache.incr(name, delta=delta)


def increase_shards(name, num):
    """
    Increase the number of shards for a given sharded counter.
    Will never decrease the number of shards.
    """

# Path: counters/models.py
# class Shard(db.Model):
#     name = db.StringProperty(required=True)
#     count = db.IntegerProperty(required=True, default=0)
# 
# class Config(db.Model):
#     name = db.StringProperty(required=True)
#     num_shards = db.IntegerProperty(required=True, default=20)


# Path: counters/utils.py
import random
from google.appengine.ext import db
from google.appengine.api import memcache
from counters.models import Shard, Config

        for counter in Shard.all().filter('name = ', name):
            total += counter.count
        memcache.add(name, str(total), 60)
    return total


def increment(name, delta=1):
    """
    Increment the value for a given sharded counter.
    """
    config = Config.get_or_insert(name, name=name)

    def txn():
        index = random.randint(1, config.num_shards)
        shard_name = name + str(index)
        counter = Shard.get_by_key_name(shard_name)
        if counter is None:
            counter = Shard(key_name=shard_name, name=name)
        counter.count += delta
        counter.put()

    db.run_in_transaction(txn)
    memcache.incr(name, delta=delta)


def increase_shards(name, num):
    """
    Increase the number of shards for a given sharded counter.
    Will never decrease the number of shards.
    """

    config = Config.get_or_insert(name, name=name)