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(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"
103 chunk = connection.read()
107 chunk = connection.read()
108 json = "".join(chunks)
110 if "Content-Length" in connection.info():
111 assert len(json) == int(connection.info()["Content-Length"]), "The packet header promised %s of data but only was able to read %s of data" % (
112 connection.info()["Content-Length"],
118 def get(self, **params):
119 "Get the XML response for the passed `params`."
120 params['api_key'] = self._apiKey
121 params['format'] = 'json'
122 params['api_sig'] = self._sign(params)
124 connection = self.open_url(SERVICE_URL, params)
125 json = self.read(connection, 5)
127 data = DottedDict('ROOT', parse_json(json))
130 if rsp.stat == 'fail':
131 raise RTMAPIError, 'API call failed - %s (%s)' % (
132 rsp.err.msg, rsp.err.code)
136 def getNewFrob(self):
137 rsp = self.get(method='rtm.auth.getFrob')
138 self._authInfo.dataReceived('frob', rsp.frob)
141 def getAuthURL(self):
143 frob = self._authInfo.get('frob')
144 except AuthStateMachine.NoData:
145 frob = self.getNewFrob()
148 'api_key': self._apiKey,
152 params['api_sig'] = self._sign(params)
153 return AUTH_SERVICE_URL + '?' + urllib.urlencode(params)
156 frob = self._authInfo.get('frob')
157 rsp = self.get(method='rtm.auth.getToken', frob=frob)
158 self._authInfo.dataReceived('token', rsp.auth.token)
159 return rsp.auth.token
162 class RTMAPICategory(object):
163 "See the `API` structure and `RTM.__init__`"
165 def __init__(self, rtm, prefix, methods):
166 self._rtm = weakref.ref(rtm)
167 self._prefix = prefix
168 self._methods = methods
170 def __getattr__(self, attr):
171 if attr not in self._methods:
172 raise AttributeError, 'No such attribute: %s' % attr
174 rargs, oargs = self._methods[attr]
175 if self._prefix == 'tasksNotes':
176 aname = 'rtm.tasks.notes.%s' % attr
178 aname = 'rtm.%s.%s' % (self._prefix, attr)
179 return lambda **params: self.callMethod(
180 aname, rargs, oargs, **params
183 def callMethod(self, aname, rargs, oargs, **params):
185 for requiredArg in rargs:
186 if requiredArg not in params:
187 raise TypeError, 'Required parameter (%s) missing' % requiredArg
190 if param not in rargs + oargs:
191 warnings.warn('Invalid parameter (%s)' % param)
193 return self._rtm().get(method=aname,
194 auth_token=self._rtm()._authInfo.get('token'),
198 def sortedItems(dictionary):
199 "Return a list of (key, value) sorted based on keys"
200 keys = dictionary.keys()
203 yield key, dictionary[key]
206 class DottedDict(object):
207 "Make dictionary items accessible via the object-dot notation."
209 def __init__(self, name, dictionary):
212 if isinstance(dictionary, dict):
213 for key, value in dictionary.items():
214 if isinstance(value, dict):
215 value = DottedDict(key, value)
216 elif isinstance(value, (list, tuple)):
217 value = [DottedDict('%s_%d' % (key, i), item)
218 for i, item in enumerate(value)]
219 setattr(self, key, value)
222 children = [c for c in dir(self) if not c.startswith('_')]
223 return '<dotted %s: %s>' % (
228 children = [(c, getattr(self, c)) for c in dir(self) if not c.startswith('_')]
229 return '{dotted %s: %s}' % (
232 ('%s: "%s"' % (k, str(v)))
233 for (k, v) in children)
237 def safer_eval(string):
239 return eval(string, {}, {})
240 except SyntaxError, e:
244 newE = RTMParseError("Error parseing json")
250 parse_json = simplejson.loads
252 parse_json = safer_eval
258 [('auth_token'), ()],
266 [('timeline', 'contact'), ()],
268 [('timeline', 'contact_id'), ()],
274 [('timeline', 'group'), ()],
276 [('timeline', 'group_id', 'contact_id'), ()],
278 [('timeline', 'group_id'), ()],
282 [('timeline', 'group_id', 'contact_id'), ()],
286 [('timeline', 'name'), ('filter'), ()],
288 [('timeline', 'list_id'), ()],
290 [('timeline', 'list_id'), ()],
294 [('timeline'), ('list_id'), ()],
296 [('timeline', 'list_id', 'name'), ()],
298 [('timeline'), ('list_id'), ()],
306 [('methodName',), ()],
316 [('timeline', 'name',), ('list_id', 'parse',)],
318 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'tags'),
321 [('timeline', 'list_id', 'taskseries_id', 'task_id',), ()],
323 [('timeline', 'list_id', 'taskseries_id', 'task_id'), ()],
326 ('list_id', 'filter', 'last_sync')],
328 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'direction'),
331 [('timeline', 'from_list_id', 'to_list_id', 'taskseries_id', 'task_id'),
334 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
337 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'tags'),
340 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
341 ('due', 'has_due_time', 'parse')],
343 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
346 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
349 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'name'),
352 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
355 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
358 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
361 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
364 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
369 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'note_title', 'note_text'), ()],
371 [('timeline', 'note_id'), ()],
373 [('timeline', 'note_id', 'note_title', 'note_text'), ()],
383 [('to_timezone',), ('from_timezone', 'to_timezone', 'time')],
385 [('text',), ('timezone', 'dateformat')],
397 [('timeline', 'transaction_id'), ()],