I use the following code to get entity based on urlsafe key
given:
q_key = ndb.Key(urlsafe=key)
q = q_key.get()
return q
But in case there is no such entity with given urlsafe key, it return
ProtocolBufferDecodeError: Unable to merge from string
on the first line, when I would expect q
to be equal to None
. Is there any other correct way to handle such case except of catching ProtocolBufferDecodeError
exception?
There is an open bug report for it here
The workaround is...
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'm a little puzzled as to why this isn't a more common complaint yet. Doesn't anyone test their urls with invalid keys?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With