I'm working on a counter for an App Engine application and am following the example outlined here http://blog.notdot.net/2010/04/High-concurrency-counters-without-sharding
I'm having trouble understanding the need for the following lines:
counter = cls.get_by_key_name(name)
if not counter:
counter = cls()
It seems an increment was requested for the instance, and then when that increment was to be applied to the datastore, the instance couldn't be found and was replaced with a new one.
The same pattern is used on the Sharding Counters example code.google.com/appengine/articles/sharding_counters.html
counter = SimpleCounterShard.get_by_key_name(shard_name)
if counter is None:
counter = SimpleCounterShard(key_name=shard_name)
In this case, the key_name is consistent between the one that wasn't found and the one that is created, so when counter.put() is eventually called it seems the new one will overwrite the not-found one.
My usage is similar to this example, which is based off the first example above: https://github.com/pamelafox/ragetube/blob/master/models.py
I'm reading line 66 as "a song was viewed and it's time to update its viewcount. Fetch the song, but if you can't, create a new song and give it this count". That can't be right.
Why would get_by_key_name() fail to return a record? Is there some default behavior that makes the first example work (ie, should a key_name of some kind be supplied)? What situation might I find myself in if I simply returned from the function if the instance couldn't be found?