Don't assume request response is always JSON

If the response's content-type is not one of the two json mimetypes
iCloud will send us we need to return early, not try to parse the
error messsage out of an invalid json object.

For added safety we wrap the JSON decoding in a try/except, so that
malformed JSON data will not result in an exception from that part
of the code (though it will likely still raise at a later point when
the JSON data is parsed in service logic).

Fixes #71
This commit is contained in:
Tor Arne Vestbø 2016-03-09 00:56:38 +01:00
parent 8dc3f524ad
commit c96a3bdc9f

View file

@ -63,10 +63,17 @@ class PyiCloudSession(requests.Session):
response = super(PyiCloudSession, self).request(*args, **kwargs) response = super(PyiCloudSession, self).request(*args, **kwargs)
json = None json_mimetypes = ['application/json', 'text/json']
if 'application/json' in response.headers['Content-Type']: if not response.headers['Content-Type'] in json_mimetypes:
return response
try:
json = response.json() json = response.json()
logger.debug(json) except:
logger.warning('Failed to parse response with JSON mimetype')
return response
logger.debug(json)
reason = json.get('errorMessage') or json.get('reason') reason = json.get('errorMessage') or json.get('reason')
if not reason and isinstance(json.get('error'), six.string_types): if not reason and isinstance(json.get('error'), six.string_types):