From c96a3bdc9f7d3b313b89f16a8c1e6a36bd92d14e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tor=20Arne=20Vestb=C3=B8?= Date: Wed, 9 Mar 2016 00:56:38 +0100 Subject: [PATCH] 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 --- pyicloud/base.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/pyicloud/base.py b/pyicloud/base.py index c0b493b..cc9a4a5 100644 --- a/pyicloud/base.py +++ b/pyicloud/base.py @@ -63,10 +63,17 @@ class PyiCloudSession(requests.Session): response = super(PyiCloudSession, self).request(*args, **kwargs) - json = None - if 'application/json' in response.headers['Content-Type']: + json_mimetypes = ['application/json', 'text/json'] + if not response.headers['Content-Type'] in json_mimetypes: + return response + + try: 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') if not reason and isinstance(json.get('error'), six.string_types):