Preventing BadArgument key_name Errors in App Engine

A friend of mine was testing out PlopQuiz and reported to me that he wasn’t able to get past account setup. He just kept getting redirected to a 500 status code page.

In the logs, I found this unfamiliar error:

BadArgumentError: Names may not begin with a digit

It turns out that key_name values (indispensible for quick lookups and resilient cross-entity references) can’t begin with a number. For people like my usability tester who want to be as cool as 50 Cent and start their name with a number, here’s some code that checks for and fixes the BadArgument:

try:
    int(key_name[0]) #check to see if key_name starts with an integer
    key_name = "prefix" + key_name
except ValueError: pass # key_name doesn't start with integer

“prefix” can be any string - extra credit for profanity, as usual. Make sure to put this snippet at the right spot in your code, especially if you’re planning on using the key_name as a reference between entities.

This snippet is also at the google app engine cookbook.

This was posted 2 years ago. Notes.