Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly handle wrong urlsafe key provided? [duplicate]

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?

like image 998
LA_ Avatar asked Dec 22 '13 17:12

LA_


1 Answers

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?

like image 64
John Mee Avatar answered Oct 15 '22 22:10

John Mee