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)
94 def get(self, **params):
95 "Get the XML response for the passed `params`."
96 params['api_key'] = self._apiKey
97 params['format'] = 'json'
98 params['api_sig'] = self._sign(params)
100 connection = self.open_url(SERVICE_URL, params)
102 # It appears that urllib uses the non-blocking variant of file objects
103 # which means reads might not always be complete, so grabbing as much
104 # of the data as possible with a sleep in between to give it more time
107 chunk = connection.read()
111 chunk = connection.read()
112 json = "".join(chunks)
114 if "Content-Length" in connection.info():
115 assert len(json) == int(connection.info()["Content-Length"]), "The packet header promised %s of data but only was able to read %s of data" % (
116 connection.info()["Content-Length"],
120 data = DottedDict('ROOT', parse_json(json))
123 if rsp.stat == 'fail':
124 raise RTMAPIError, 'API call failed - %s (%s)' % (
125 rsp.err.msg, rsp.err.code)
129 def getNewFrob(self):
130 rsp = self.get(method='rtm.auth.getFrob')
131 self._authInfo.dataReceived('frob', rsp.frob)
134 def getAuthURL(self):
136 frob = self._authInfo.get('frob')
137 except AuthStateMachine.NoData:
138 frob = self.getNewFrob()
141 'api_key': self._apiKey,
145 params['api_sig'] = self._sign(params)
146 return AUTH_SERVICE_URL + '?' + urllib.urlencode(params)
149 frob = self._authInfo.get('frob')
150 rsp = self.get(method='rtm.auth.getToken', frob=frob)
151 self._authInfo.dataReceived('token', rsp.auth.token)
152 return rsp.auth.token
155 class RTMAPICategory(object):
156 "See the `API` structure and `RTM.__init__`"
158 def __init__(self, rtm, prefix, methods):
159 self._rtm = weakref.ref(rtm)
160 self._prefix = prefix
161 self._methods = methods
163 def __getattr__(self, attr):
164 if attr not in self._methods:
165 raise AttributeError, 'No such attribute: %s' % attr
167 rargs, oargs = self._methods[attr]
168 if self._prefix == 'tasksNotes':
169 aname = 'rtm.tasks.notes.%s' % attr
171 aname = 'rtm.%s.%s' % (self._prefix, attr)
172 return lambda **params: self.callMethod(
173 aname, rargs, oargs, **params
176 def callMethod(self, aname, rargs, oargs, **params):
178 for requiredArg in rargs:
179 if requiredArg not in params:
180 raise TypeError, 'Required parameter (%s) missing' % requiredArg
183 if param not in rargs + oargs:
184 warnings.warn('Invalid parameter (%s)' % param)
186 return self._rtm().get(method=aname,
187 auth_token=self._rtm()._authInfo.get('token'),
191 def sortedItems(dictionary):
192 "Return a list of (key, value) sorted based on keys"
193 keys = dictionary.keys()
196 yield key, dictionary[key]
199 class DottedDict(object):
200 "Make dictionary items accessible via the object-dot notation."
202 def __init__(self, name, dictionary):
205 if isinstance(dictionary, dict):
206 for key, value in dictionary.items():
207 if isinstance(value, dict):
208 value = DottedDict(key, value)
209 elif isinstance(value, (list, tuple)):
210 value = [DottedDict('%s_%d' % (key, i), item)
211 for i, item in enumerate(value)]
212 setattr(self, key, value)
215 children = [c for c in dir(self) if not c.startswith('_')]
216 return '<dotted %s: %s>' % (
221 children = [(c, getattr(self, c)) for c in dir(self) if not c.startswith('_')]
222 return '{dotted %s: %s}' % (
225 ('%s: "%s"' % (k, str(v)))
226 for (k, v) in children)
230 def safer_eval(string):
232 return eval(string, {}, {})
233 except SyntaxError, e:
237 newE = RTMParseError("Error parseing json")
243 parse_json = simplejson.loads
245 parse_json = safer_eval
251 [('auth_token'), ()],
259 [('timeline', 'contact'), ()],
261 [('timeline', 'contact_id'), ()],
267 [('timeline', 'group'), ()],
269 [('timeline', 'group_id', 'contact_id'), ()],
271 [('timeline', 'group_id'), ()],
275 [('timeline', 'group_id', 'contact_id'), ()],
279 [('timeline', 'name'), ('filter'), ()],
281 [('timeline', 'list_id'), ()],
283 [('timeline', 'list_id'), ()],
287 [('timeline'), ('list_id'), ()],
289 [('timeline', 'list_id', 'name'), ()],
291 [('timeline'), ('list_id'), ()],
299 [('methodName',), ()],
309 [('timeline', 'name',), ('list_id', 'parse',)],
311 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'tags'),
314 [('timeline', 'list_id', 'taskseries_id', 'task_id',), ()],
316 [('timeline', 'list_id', 'taskseries_id', 'task_id'), ()],
319 ('list_id', 'filter', 'last_sync')],
321 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'direction'),
324 [('timeline', 'from_list_id', 'to_list_id', 'taskseries_id', 'task_id'),
327 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
330 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'tags'),
333 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
334 ('due', 'has_due_time', 'parse')],
336 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
339 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
342 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'name'),
345 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
348 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
351 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
354 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
357 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
362 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'note_title', 'note_text'), ()],
364 [('timeline', 'note_id'), ()],
366 [('timeline', 'note_id', 'note_title', 'note_text'), ()],
376 [('to_timezone',), ('from_timezone', 'to_timezone', 'time')],
378 [('text',), ('timezone', 'dateformat')],
390 [('timeline', 'transaction_id'), ()],