From 78a508d304933c124c68a9f9fc0ee6a093f1a686 Mon Sep 17 00:00:00 2001 From: Joe Gregorio Date: Tue, 26 Oct 2010 16:36:36 -0400 Subject: [PATCH] Be robust in what you accept, which might be a JSON object w/o an outer wrapper 'data' object. --- apiclient/discovery.py | 5 ++++- tests/test_json_model.py | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/apiclient/discovery.py b/apiclient/discovery.py index a5b7c9a..fe98db1 100644 --- a/apiclient/discovery.py +++ b/apiclient/discovery.py @@ -111,7 +111,10 @@ class JsonModel(object): if resp.status == 204: # A 204: No Content response should be treated differently to all the other success states return simplejson.loads('{}') - return simplejson.loads(content)['data'] + body = simplejson.loads(content) + if isinstance(body, dict) and 'data' in body: + body = body['data'] + return body else: logging.debug('Content from bad request was: %s' % content) if resp.get('content-type', '').startswith('application/json'): diff --git a/tests/test_json_model.py b/tests/test_json_model.py index a8da2b6..2bf0302 100644 --- a/tests/test_json_model.py +++ b/tests/test_json_model.py @@ -140,5 +140,23 @@ class Model(unittest.TestCase): content = model.response(resp, content) self.assertEqual(content, 'is good') + def test_good_response_wo_data(self): + model = JsonModel() + resp = httplib2.Response({'status': '200'}) + resp.reason = 'OK' + content = '{"foo": "is good"}' + + content = model.response(resp, content) + self.assertEqual(content, {'foo': 'is good'}) + + def test_good_response_wo_data_str(self): + model = JsonModel() + resp = httplib2.Response({'status': '200'}) + resp.reason = 'OK' + content = '"data goes here"' + + content = model.response(resp, content) + self.assertEqual(content, 'data goes here') + if __name__ == '__main__': unittest.main()