Python Google App Engine: A better way of saying, "If an object does not exist in the datastore, do something"?
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!
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.
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.
精彩评论