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)
113 if "Content-Length" in connection.info():
114 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"],
119 data = DottedDict('ROOT', parse_json(json))
122 if rsp.stat == 'fail':
123 raise RTMAPIError, 'API call failed - %s (%s)' % (
124 rsp.err.msg, rsp.err.code)
128 def getNewFrob(self):
129 rsp = self.get(method='rtm.auth.getFrob')
130 self._authInfo.dataReceived('frob', rsp.frob)
133 def getAuthURL(self):
135 frob = self._authInfo.get('frob')
136 except AuthStateMachine.NoData:
137 frob = self.getNewFrob()
140 'api_key': self._apiKey,
144 params['api_sig'] = self._sign(params)
145 return AUTH_SERVICE_URL + '?' + urllib.urlencode(params)
148 frob = self._authInfo.get('frob')
149 rsp = self.get(method='rtm.auth.getToken', frob=frob)
150 self._authInfo.dataReceived('token', rsp.auth.token)
151 return rsp.auth.token
154 class RTMAPICategory(object):
155 "See the `API` structure and `RTM.__init__`"
157 def __init__(self, rtm, prefix, methods):
158 self._rtm = weakref.ref(rtm)
159 self._prefix = prefix
160 self._methods = methods
162 def __getattr__(self, attr):
163 if attr not in self._methods:
164 raise AttributeError, 'No such attribute: %s' % attr
166 rargs, oargs = self._methods[attr]
167 if self._prefix == 'tasksNotes':
168 aname = 'rtm.tasks.notes.%s' % attr
170 aname = 'rtm.%s.%s' % (self._prefix, attr)
171 return lambda **params: self.callMethod(
172 aname, rargs, oargs, **params
175 def callMethod(self, aname, rargs, oargs, **params):
177 for requiredArg in rargs:
178 if requiredArg not in params:
179 raise TypeError, 'Required parameter (%s) missing' % requiredArg
182 if param not in rargs + oargs:
183 warnings.warn('Invalid parameter (%s)' % param)
185 return self._rtm().get(method=aname,
186 auth_token=self._rtm()._authInfo.get('token'),
190 def sortedItems(dictionary):
191 "Return a list of (key, value) sorted based on keys"
192 keys = dictionary.keys()
195 yield key, dictionary[key]
198 class DottedDict(object):
199 "Make dictionary items accessible via the object-dot notation."
201 def __init__(self, name, dictionary):
204 if isinstance(dictionary, dict):
205 for key, value in dictionary.items():
206 if isinstance(value, dict):
207 value = DottedDict(key, value)
208 elif isinstance(value, (list, tuple)):
209 value = [DottedDict('%s_%d' % (key, i), item)
210 for i, item in enumerate(value)]
211 setattr(self, key, value)
214 children = [c for c in dir(self) if not c.startswith('_')]
215 return '<dotted %s: %s>' % (
220 children = [(c, getattr(self, c)) for c in dir(self) if not c.startswith('_')]
221 return '{dotted %s: %s}' % (
224 ('%s: "%s"' % (k, str(v)))
225 for (k, v) in children)
229 def safer_eval(string):
231 return eval(string, {}, {})
232 except SyntaxError, e:
236 newE = RTMParseError("Error parseing json")
242 parse_json = simplejson.loads
244 parse_json = safer_eval
250 [('auth_token'), ()],
258 [('timeline', 'contact'), ()],
260 [('timeline', 'contact_id'), ()],
266 [('timeline', 'group'), ()],
268 [('timeline', 'group_id', 'contact_id'), ()],
270 [('timeline', 'group_id'), ()],
274 [('timeline', 'group_id', 'contact_id'), ()],
278 [('timeline', 'name'), ('filter'), ()],
280 [('timeline', 'list_id'), ()],
282 [('timeline', 'list_id'), ()],
286 [('timeline'), ('list_id'), ()],
288 [('timeline', 'list_id', 'name'), ()],
290 [('timeline'), ('list_id'), ()],
298 [('methodName',), ()],
308 [('timeline', 'name',), ('list_id', 'parse',)],
310 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'tags'),
313 [('timeline', 'list_id', 'taskseries_id', 'task_id',), ()],
315 [('timeline', 'list_id', 'taskseries_id', 'task_id'), ()],
318 ('list_id', 'filter', 'last_sync')],
320 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'direction'),
323 [('timeline', 'from_list_id', 'to_list_id', 'taskseries_id', 'task_id'),
326 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
329 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'tags'),
332 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
333 ('due', 'has_due_time', 'parse')],
335 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
338 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
341 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'name'),
344 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
347 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
350 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
353 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
356 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
361 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'note_title', 'note_text'), ()],
363 [('timeline', 'note_id'), ()],
365 [('timeline', 'note_id', 'note_title', 'note_text'), ()],
375 [('to_timezone',), ('from_timezone', 'to_timezone', 'time')],
377 [('text',), ('timezone', 'dateformat')],
389 [('timeline', 'transaction_id'), ()],