I'm really stuck with this! I'm getting some product data from Amazon, which is returned as an XML. When the search keyword is valid, it returns the XML with nodes Items
> Item
. With a wrong keyword, or a keyword that doesn't return valid results, the Item
node is absent. I'm using some function to convert this XML to Object for easy parsing. Then use hasattr
to recursively check various nodes.
data = someXMLConverter(xml)
#works
if hasattr(data, 'Items'):
#doesn't work
if hasattr(data.Items, 'Item'):
#some processing here
else:
return 'Error'
else:
return 'Error'
Even when the Item
node is absent, hasattr
returns true. So in case of an error, my site explodes!
Any ideas?
Sample XML:
<ItemSearchResponse>
<OperationRequest>
<HTTPHeaders><Header Name="UserAgent" Value="Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0"/></HTTPHeaders>
<RequestId>a393e9db-b86e-41de-965d-922c947056ff</RequestId>
<Arguments>
<Argument Name="Operation" Value="ItemSearch"/>
<Argument Name="Service" Value="AWSECommerceService"/>
<Argument Name="Signature" Value="z/R9HjzqukC6J53bmF4LPxh/xtlwBv9k+u6QjGsgFmA="/>
<Argument Name="ItemPage" Value="1"/>
<Argument Name="AssociateTag" Value="rutwsblog-20"/>
<Argument Name="Version" Value="2006-09-11"/>
<Argument Name="Keywords" Value="dggd"/>
<Argument Name="AWSAccessKeyId" Value="AKIAJ3TAUM7ANQFQYP7Q"/>
<Argument Name="Timestamp" Value="2013-05-17T16:50:55"/>
<Argument Name="ResponseGroup" Value="Medium"/>
<Argument Name="SearchIndex" Value="Books"/>
</Arguments>
<RequestProcessingTime>0.0217790000000000</RequestProcessingTime>
</OperationRequest>
<Items>
<Request>
<IsValid>True</IsValid>
<ItemSearchRequest>
<ItemPage>1</ItemPage>
<Keywords>dggd</Keywords>
<ResponseGroup>Medium</ResponseGroup>
<SearchIndex>Books</SearchIndex>
</ItemSearchRequest>
<Errors>
<Error>
<Code>AWS.ECommerceService.NoExactMatches</Code>
<Message>We did not find any matches for your request.</Message>
</Error>
</Errors>
</Request>
<TotalResults>0</TotalResults>
<TotalPages>0</TotalPages>
<MoreSearchResultsUrl>http://www.amazon.com/gp/redirect.html?camp=2025&creative=386001&location=http%3A%2F%2Fwww.amazon.com%2Fgp%2Fsearch%3Fkeywords%3Ddggd%26url%3Dsearch-alias%253Dstripbooks&linkCode=xm2&tag=xxxx-20&SubscriptionId=xxxx</MoreSearchResultsUrl>
</Items>
</ItemSearchResponse>
You can use the following to avoid also processing when you get None
data = someXMLConverter(xml)
if hasattr(data, 'Items'):
if hasattr(data.Items, 'Item') and data.Items.Item is not None:
#some processing here
else:
return 'Error'
else:
return 'Error'
Since the if statement is short-circuited if hasattr
returns False
we can safely check for None
right after.