Cleaning up the code, improving error handling and performing a minor optimization
authorEd Page <eopage@byu.net>
Thu, 16 Apr 2009 13:40:30 +0000 (08:40 -0500)
committerEd Page <eopage@byu.net>
Thu, 16 Apr 2009 13:40:30 +0000 (08:40 -0500)
src/rtm_api.py

index d513fc8..e53009b 100644 (file)
@@ -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 = {