I’m doing my first small project in Python(GAE), and there’s no difficulty in operating GAE’s database using queries. But when it comes to editing single Entity I face a problem.
All I need is a simple counter which would increment on every site visit.
So I create an Entity (this is done once, just to create Entity, then this code is removed from project) by:
counter_name = 'default_counter'
def counter_key(counter_n=None):
return db.Key.from_path('Counter', counter_name)
class Counter(db.Model):
amount = db.IntegerProperty()
class CounterClass(webapp.RequestHandler):
def get(self):
counter = Counter(counter_key(counter_name))
counter.amount = 0
counter.put()
It is ok.
But when I try to increment it, using:
counter = db.get(db.Key.from_path('Counter', 'default_counter'))
counter.amount += 1
counter.put()
I get this Error.
ERROR 2011-09-06 21:49:41,562 _webapp25.py:464] ‘NoneType’ object
has no attribute ‘amount’ Traceback (most recent call last): File
“C:\Program Files
(x86)\Google\google_appengine\google\appengine\ext\webapp_webapp25.py”,
line 703, in call
handler.post(*groups) File
“H:\gae-bin\counter.py”, line
48, in post
counter.amount += 1 AttributeError: ‘NoneType’ object has no
attribute ‘amount’
I checked different variations, but still cant change Entity’s value.
What am I doing wrong?
Thanks in advance.
The code you use to create the
Counterentity is likely wrong. What it does is creating aCounterentity whose parent isCounterwith keyname equal todefault_counter. That doesn’t seem to be what your want, as evidenced by code you use to update the counter.You need to assign the keyname of your
Counterentity via one of the following ways:Note that in general it is bad idea to have a visit counter like that. GAE entities have a limti for 5 updates per seconds so if you ever scale beyond that, you will run into problems.
Common technique for dealing with the update limitation is to use sharding counters as described here: http://code.google.com/intl/pl/appengine/articles/sharding_counters.html . A combination of datastore and memcache is also an option if you don’t mind occasionally losing some counter increments.