Issue
I would like to get the key name from the Python KeyError
exception:
For example:
myDict = {'key1':'value1'}
try:
x1 = myDict['key1']
x2 = myDict['key2']
except KeyError as e:
# here i want to use the name of the key that was missing which is 'key2' in this example
print error_msg[missing_key]
i have already tried this
print e
print e.args
print e.message
my code is inside django view !
if i use ipython for example and try e.arg or e.message it works fine. but then i try it while inside a django view i get this results:
"Key 'key2' not found in <QueryDict: {u'key1': [u'value']}>"
("Key 'key2' not found in <QueryDict: {u'key1': [u'value']}>",)
Key 'key2' not found in <QueryDict: {u'key1': [u'value']}>
while i just want the 'key2'
Solution
As your dictionary is actually a QueryDict
, and therefore returns a different error message, you will need to parse the exception message to return the first word in single quotes:
import re
#...
except KeyError as e:
m = re.search("'([^']*)'", e.message)
key = m.group(1)
Answered By - Jon Cairns
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.