From 2036f410761011027f7c63d36ae7213c88333d5e Mon Sep 17 00:00:00 2001 From: Ed Page Date: Thu, 16 Apr 2009 08:40:30 -0500 Subject: [PATCH] Cleaning up the code, improving error handling and performing a minor optimization --- src/rtm_api.py | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/src/rtm_api.py b/src/rtm_api.py index d513fc8..e53009b 100644 --- a/src/rtm_api.py +++ b/src/rtm_api.py @@ -8,6 +8,7 @@ Python library for Remember The Milk API import weakref import warnings import urllib +import urllib2 from md5 import md5 _use_simplejson = False @@ -32,6 +33,10 @@ class RTMAPIError(RTMError): pass +class RTMParseError(RTMError): + pass + + class AuthStateMachine(object): """If the state is in those setup for the machine, then return the datum sent. Along the way, it is an automatic call if the @@ -83,7 +88,7 @@ class RTMapi(object): if queryArgs: url += '?' + urllib.urlencode(queryArgs) warnings.warn("Performing download of %s" % url, stacklevel=5) - return urllib.urlopen(url) + return urllib2.urlopen(url) def get(self, **params): "Get the XML response for the passed `params`." @@ -91,12 +96,9 @@ class RTMapi(object): params['format'] = 'json' params['api_sig'] = self._sign(params) - json = self.open_url(SERVICE_URL, params).read() - - if _use_simplejson: - data = DottedDict('ROOT', simplejson.loads(json)) - else: - data = DottedDict('ROOT', safer_eval(json)) + connection = self.open_url(SERVICE_URL, params) + json = connection.read() + data = DottedDict('ROOT', parse_json(json)) rsp = data.rsp if rsp.stat == 'fail': @@ -207,7 +209,18 @@ class DottedDict(object): def safer_eval(string): - return eval(string, {}, {}) + try: + return eval(string, {}, {}) + except SyntaxError, e: + newE = RTMParseError("Error parseing json") + newE.error = e + raise newE + + +if _use_simplejson: + parse_json = simplejson.loads +else: + parse_json = safer_eval API = { -- 1.7.9.5