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

2

6

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?

Lin answered 22/12, 2013 at 17:10 Comment(2)
catching ProtocolBufferDecodeError and returning None seems fine for me.Provenience
@DanCornilescu, this question has been asked before in 2015 (when my question as of 2013), ooook :)Lin
J
7

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?

Jewell answered 3/10, 2014 at 8:46 Comment(1)
Still nothing for this? I was writing tests today and hit this. In my case previous App Engine projects didn't use a urlsafe key, so that's why I never hit it previously. Still it's kind of odd that there's not a better way to handle this.Cowage
K
0

You can try this

try:
    q_key = ndb.Key(urlsafe=key)
    q = q_key.get()
except ProtocolBufferDecodeError:    
    q = None
return q
Kentiga answered 24/12, 2013 at 7:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.