views:

104

answers:

2

I am asking because the way I have it right now seems really strange. Basically, I am saying, "If there is an exception thrown, do something. Else, do nothing." Here is some sample code:

 try:
        db.get(db.Key(uid))
 except:
        newUser = User(key_name=str(uid)) 
        newUser.first_name = self.request.get("first")
        newUser.last_name = self.request.get("last")
        newUser.email = self.request.get("email") 
        newUser.phone = self.request.get("phone")
        db.put(newUser)

Thanks!

+1  A: 

Does db.Key return None if there is no user with the given uid? If so, you could just do:

if db.Key(uid) == None:
    newUser = User(key_name=str(uid)) 
    newUser.first_name = self.request.get("first")
    newUser.last_name = self.request.get("last")
    newUser.email = self.request.get("email") 
    newUser.phone = self.request.get("phone")
    db.put(newUser)

EDIT: going by your comment, you get an exception anyway, so unless you have some other way of checking for nonexistence of a User, you may as well stick with what you have. You could always do it the other way around and put the bulk of the code in the try block, though, assuming that an exception will be thrown when trying to add a User with a Key that already exists in the database, like so:

try:
    newUser = User(key_name=str(uid)) 
    newUser.first_name = self.request.get("first")
    newUser.last_name = self.request.get("last")
    newUser.email = self.request.get("email") 
    newUser.phone = self.request.get("phone")
    db.put(newUser)
except:
    pass

Or something like that.

JAB
It doesn't return None. I get something called BadKeyError. I still feel like my way is an unconventional way.
ayanonagon
@ayanonagon: Updated my answer, then, but it seems hwiechers has what you want.
JAB
BadKeyError is thrown when the key is invalid - not when it's valid but does not exist in the datastore. You need to distinguish between the case when you have an invalid key, and the case when you have a valid but nonexistent key.
Nick Johnson
+5  A: 

Use User.get_by_key_name(str(uid)) instead. It will return None if the entity doesn't exist.

See http://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_get_by_key_name for details.

User.get_or_insert(str(uid)) might also be a good fit for what you're trying to do.

hwiechers