How to handle the wrong urlsafe key correctly?

I use the following code to get an urlsafe key based entity:

 q_key = ndb.Key(urlsafe=key) q = q_key.get() return q 

But if such an object with the specified urlsafe key does not exist, it returns ProtocolBufferDecodeError: Unable to merge from string in the first line when I expect q to be None . Is there any other correct way to handle this case other than a ProtocolBufferDecodeError exception?

+6
source share
2 answers

There is an error report here for errors

Workaround ...

 from google.net.proto.ProtocolBuffer import ProtocolBufferDecodeError try: q_key = ndb.Key(urlsafe=key) q = q_key.get() except ProtocolBufferDecodeError: q = None return q 

I am a little puzzled by why this is not the most common complaint. Does anyone not test their urls with invalid keys?

+7
source

You can try this

 try: q_key = ndb.Key(urlsafe=key) q = q_key.get() except ProtocolBufferDecodeError: q = None return q 
0
source

All Articles