3 Python library for Remember The Milk API
5 @note For help, see http://www.rememberthemilk.com/services/api/methods/
15 _use_simplejson = False
18 _use_simplejson = True
23 __author__ = 'Sridhar Ratnakumar <http://nearfar.org/>'
25 SERVICE_URL = 'http://api.rememberthemilk.com/services/rest/'
26 AUTH_SERVICE_URL = 'http://www.rememberthemilk.com/services/auth/'
29 class RTMError(StandardError):
33 class RTMAPIError(RTMError):
37 class RTMParseError(RTMError):
41 class AuthStateMachine(object):
42 """If the state is in those setup for the machine, then return
43 the datum sent. Along the way, it is an automatic call if the
47 class NoData(RTMError):
50 def __init__(self, states):
54 def dataReceived(self, state, datum):
55 if state not in self.states:
56 raise RTMError, "Invalid state <%s>" % state
57 self.data[state] = datum
60 if state in self.data:
61 return self.data[state]
63 raise AuthStateMachine.NoData('No data for <%s>' % state)
68 def __init__(self, userID, apiKey, secret, token=None):
72 self._authInfo = AuthStateMachine(['frob', 'token'])
74 # this enables one to do 'rtm.tasks.getList()', for example
75 for prefix, methods in API.items():
77 RTMAPICategory(self, prefix, methods))
80 self._authInfo.dataReceived('token', token)
82 def _sign(self, params):
83 "Sign the parameters with MD5 hash"
84 pairs = ''.join(['%s%s' % (k, v) for (k, v) in sortedItems(params)])
85 return hashlib.md5(self._secret+pairs).hexdigest()
88 def open_url(url, queryArgs=None):
90 url += '?' + urllib.urlencode(queryArgs)
91 warnings.warn("Performing download of %s" % url, stacklevel=5)
92 return urllib2.urlopen(url)
95 def read_by_length(connection, timeout):
96 # It appears that urllib uses the non-blocking variant of file objects
97 # which means reads might not always be complete, so grabbing as much
98 # of the data as possible with a sleep in between to give it more time
100 contentLengthField = "Content-Length"
101 assert contentLengthField in connection.info(), "Connection didn't provide content length info"
102 specifiedLength = int(connection.info()["Content-Length"])
106 chunk = connection.read()
108 actuallyRead += len(chunk)
109 if actuallyRead == specifiedLength:
114 chunk = connection.read()
116 json = "".join(chunks)
118 if "Content-Length" in connection.info():
119 assert len(json) == int(connection.info()["Content-Length"]), "The packet header promised %s of data but only was able to read %s of data" % (
120 connection.info()["Content-Length"],
127 def read_by_guess(connection, timeout):
128 # It appears that urllib uses the non-blocking variant of file objects
129 # which means reads might not always be complete, so grabbing as much
130 # of the data as possible with a sleep in between to give it more time
134 chunk = connection.read()
135 while chunk and 0 < timeout:
139 chunk = connection.read()
141 json = "".join(chunks)
143 if "Content-Length" in connection.info():
144 assert len(json) == int(connection.info()["Content-Length"]), "The packet header promised %s of data but only was able to read %s of data" % (
145 connection.info()["Content-Length"],
151 def get(self, **params):
152 "Get the XML response for the passed `params`."
153 params['api_key'] = self._apiKey
154 params['format'] = 'json'
155 params['api_sig'] = self._sign(params)
157 connection = self.open_url(SERVICE_URL, params)
158 json = self.read_by_guess(connection, 5)
159 # json = self.read_by_length(connection, 5)
161 data = DottedDict('ROOT', parse_json(json))
164 if rsp.stat == 'fail':
165 raise RTMAPIError, 'API call failed - %s (%s)' % (
166 rsp.err.msg, rsp.err.code)
170 def getNewFrob(self):
171 rsp = self.get(method='rtm.auth.getFrob')
172 self._authInfo.dataReceived('frob', rsp.frob)
175 def getAuthURL(self):
177 frob = self._authInfo.get('frob')
178 except AuthStateMachine.NoData:
179 frob = self.getNewFrob()
182 'api_key': self._apiKey,
186 params['api_sig'] = self._sign(params)
187 return AUTH_SERVICE_URL + '?' + urllib.urlencode(params)
190 frob = self._authInfo.get('frob')
191 rsp = self.get(method='rtm.auth.getToken', frob=frob)
192 self._authInfo.dataReceived('token', rsp.auth.token)
193 return rsp.auth.token
196 class RTMAPICategory(object):
197 "See the `API` structure and `RTM.__init__`"
199 def __init__(self, rtm, prefix, methods):
200 self._rtm = weakref.ref(rtm)
201 self._prefix = prefix
202 self._methods = methods
204 def __getattr__(self, attr):
205 if attr not in self._methods:
206 raise AttributeError, 'No such attribute: %s' % attr
208 rargs, oargs = self._methods[attr]
209 if self._prefix == 'tasksNotes':
210 aname = 'rtm.tasks.notes.%s' % attr
212 aname = 'rtm.%s.%s' % (self._prefix, attr)
213 return lambda **params: self.callMethod(
214 aname, rargs, oargs, **params
217 def callMethod(self, aname, rargs, oargs, **params):
219 for requiredArg in rargs:
220 if requiredArg not in params:
221 raise TypeError, 'Required parameter (%s) missing' % requiredArg
224 if param not in rargs + oargs:
225 warnings.warn('Invalid parameter (%s)' % param)
227 return self._rtm().get(method=aname,
228 auth_token=self._rtm()._authInfo.get('token'),
232 def sortedItems(dictionary):
233 "Return a list of (key, value) sorted based on keys"
234 keys = dictionary.keys()
237 yield key, dictionary[key]
240 class DottedDict(object):
241 "Make dictionary items accessible via the object-dot notation."
243 def __init__(self, name, dictionary):
246 if isinstance(dictionary, dict):
247 for key, value in dictionary.items():
248 if isinstance(value, dict):
249 value = DottedDict(key, value)
250 elif isinstance(value, (list, tuple)):
251 value = [DottedDict('%s_%d' % (key, i), item)
252 for i, item in enumerate(value)]
253 setattr(self, key, value)
256 children = [c for c in dir(self) if not c.startswith('_')]
257 return '<dotted %s: %s>' % (
262 children = [(c, getattr(self, c)) for c in dir(self) if not c.startswith('_')]
263 return '{dotted %s: %s}' % (
266 ('%s: "%s"' % (k, str(v)))
267 for (k, v) in children)
271 def safer_eval(string):
273 return eval(string, {}, {})
274 except SyntaxError, e:
278 newE = RTMParseError("Error parseing json")
284 parse_json = simplejson.loads
286 parse_json = safer_eval
292 [('auth_token'), ()],
300 [('timeline', 'contact'), ()],
302 [('timeline', 'contact_id'), ()],
308 [('timeline', 'group'), ()],
310 [('timeline', 'group_id', 'contact_id'), ()],
312 [('timeline', 'group_id'), ()],
316 [('timeline', 'group_id', 'contact_id'), ()],
320 [('timeline', 'name'), ('filter'), ()],
322 [('timeline', 'list_id'), ()],
324 [('timeline', 'list_id'), ()],
328 [('timeline'), ('list_id'), ()],
330 [('timeline', 'list_id', 'name'), ()],
332 [('timeline'), ('list_id'), ()],
340 [('methodName',), ()],
350 [('timeline', 'name',), ('list_id', 'parse',)],
352 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'tags'),
355 [('timeline', 'list_id', 'taskseries_id', 'task_id',), ()],
357 [('timeline', 'list_id', 'taskseries_id', 'task_id'), ()],
360 ('list_id', 'filter', 'last_sync')],
362 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'direction'),
365 [('timeline', 'from_list_id', 'to_list_id', 'taskseries_id', 'task_id'),
368 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
371 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'tags'),
374 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
375 ('due', 'has_due_time', 'parse')],
377 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
380 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
383 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'name'),
386 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
389 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
392 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
395 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
398 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
403 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'note_title', 'note_text'), ()],
405 [('timeline', 'note_id'), ()],
407 [('timeline', 'note_id', 'note_title', 'note_text'), ()],
417 [('to_timezone',), ('from_timezone', 'to_timezone', 'time')],
419 [('text',), ('timezone', 'dateformat')],
431 [('timeline', 'transaction_id'), ()],