views:

44

answers:

1

Hi,

I would like to mention before hand that I am a novice to python and with that to python platform of GAE. I have been finding this very strange error/fault when I am trying to get an entity using its key ID... Here's what I do,

I am querying the datastore entity model UserDetails for the key corresponding to the user name retrieved from UI.

src_key_str = db.GqlQuery('SELECT __key__ FROM UserDetails WHERE user_name = :uname', uname = src_username).fetch(1)
for itr1 in src_key_str:
          src_key = itr1.id_or_name()

Then using the src_key obtained I try to get the entity corresponding to the same.

accounts = UserDetails.get_by_id(src_key)

Now here when I try to access the properties of accounts using self.response.out.write(accounts.user_name), I get an error AttributeError: 'list' object has no attribute 'user_name'. Thinking that accounts was actually a list, I tried to get the first element using accounts[0] Now I get list out of bound error.

When I try hard-coding the src_key value, it works just fine but, when I pass the value to the same method I get those errors. I fail to understand why GAE behaves so in production environment and development environment. Am I missing some info on this behaviour?

EDIT : adding stack trace,

Traceback (most recent call last):
  File "/base/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 507, in __call__
    handler.get(*groups)
  File "/base/data/home/apps/bulkloader160by2/1-5.337673425692960489/new_main.py", line 93, in get
    self.response.out.write(accounts.user_name)
AttributeError: 'list' object has no attribute 'user_name'
+1  A: 

You're getting this error because 'accounts' is a list rather than a single instance. Based on your code, I can't see why this would be the case, but try doing the following:

src_key = db.GqlQuery('SELECT __key__ FROM UserDetails WHERE user_name = :uname', uname = src_username).get()
if src_key:
  account = UserDetails.get(src_key)

There's no reason to call .fetch() when you only need one object, and there's also no reason to extract the id, just to pass it to .get_by_id. In fact, if the snippet you've shown is all you're doing, simpler and faster would be:

account = db.GqlQuery('SELECT * FROM UserDetails WHERE user_name = :uname', uname = src_username).get()
Nick Johnson
If `accounts` was a list as you have suggested then I think I shouldn't be getting list out of bound error when I call `accounts[0]` right under `accounts = UserDetails.get_by_id(src_key)`, but I got that as I have mentioned in my question.
Arun
If accounts is an empty list, an out of bound error is exactly what you'd get for 'accounts[0]'. If it weren't a list, you'd get a _different_ error trying to index it.
Nick Johnson