I am writing a flask API that receives different types of nested json files. I want to do something based on different information from said files.
I sort the files based on an if statement, this is the simplified version:
if (jsonFile['data']['shape'] == "cube"):
function(jsonFile)
elif (jsonFile['data']['shape'] == "cone"):
function(jsonFile)
elif (jsonFile['data']['sphere']):
function(jsonFile)
else:
print("Unknown file")
When I send a nested json file through postman, for example one containing the sphere, I get a 500 error "KeyError: shape"
and I never reach the elif statement.
If I switch the elif statement containing the sphere with the one at the top, then only the sphere works and the rest do not. It only works for the if statement at the top, if the condition is not satisfied, it throws an error and ignores the rest of the block. Even when I send something random, I never get to the else statement.
Rest of the statements all work on their own.
Example of json file containing cube:
{
"data": {
"shape": "cube"
}
}
Example of json file containing sphere:
{
"data": {
"sphere": {
"description": "spherical"
}
}
}
This is the full error:
ERROR in app: Exception on /processshape [POST]
Traceback (most recent call last):
File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\site-packages\flask\app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\site-packages\flask\app.py", line 1822, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\site-packages\flask\app.py", line 1796, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
File "d:\python\shape-api\app.py", line 34, in processshape
if (resp['data']['shape'] == "cube"):
KeyError: 'shape'
127.0.0.1 - - [02/Feb/2023 00:03:38] "POST /processshape HTTP/1.1" 500 -
CodePudding user response:
The issue is that the if (jsonFile['data']['shape'] == "cube")
is executed.
This will execute the expression jsonFile['data']['shape']
.
jsonFile['data']
will evaluate to a dict.
However, this dict does not contain the key shape
.
Thus, a KeyError
will be thrown and the elif will not be executed.
You could fix it by changing
if (jsonFile['data']['shape'] == "cube")
to
if ('shape' in jsonFile['data'] and jsonFile['data']['shape'] == "cube")
Such that you do not try to access the value for the key shape
if it doesn't exist.
The same change must be applied to the other cases as well.
If it is not certain that the key data
is always contained in jsonFile
, you must also check for that.