3 Python library for Remember The Milk API
5 @note For help, see http://www.rememberthemilk.com/services/api/methods/
13 _use_simplejson = False
16 _use_simplejson = True
21 __author__ = 'Sridhar Ratnakumar <http://nearfar.org/>'
23 SERVICE_URL = 'http://api.rememberthemilk.com/services/rest/'
24 AUTH_SERVICE_URL = 'http://www.rememberthemilk.com/services/auth/'
27 class RTMError(StandardError):
31 class RTMAPIError(RTMError):
35 class AuthStateMachine(object):
36 """If the state is in those setup for the machine, then return
37 the datum sent. Along the way, it is an automatic call if the
41 class NoData(RTMError):
44 def __init__(self, states):
48 def dataReceived(self, state, datum):
49 if state not in self.states:
50 raise RTMError, "Invalid state <%s>" % state
51 self.data[state] = datum
54 if state in self.data:
55 return self.data[state]
57 raise AuthStateMachine.NoData('No data for <%s>' % state)
62 def __init__(self, userID, apiKey, secret, token=None):
66 self._authInfo = AuthStateMachine(['frob', 'token'])
68 # this enables one to do 'rtm.tasks.getList()', for example
69 for prefix, methods in API.items():
71 RTMAPICategory(self, prefix, methods))
74 self._authInfo.dataReceived('token', token)
76 def _sign(self, params):
77 "Sign the parameters with MD5 hash"
78 pairs = ''.join(['%s%s' % (k, v) for (k, v) in sortedItems(params)])
79 return md5(self._secret+pairs).hexdigest()
82 def open_url(url, queryArgs=None):
84 url += '?' + urllib.urlencode(queryArgs)
85 warnings.warn("Performing download of %s" % url, stacklevel=5)
86 return urllib.urlopen(url)
88 def get(self, **params):
89 "Get the XML response for the passed `params`."
90 params['api_key'] = self._apiKey
91 params['format'] = 'json'
92 params['api_sig'] = self._sign(params)
94 json = self.open_url(SERVICE_URL, params).read()
97 data = DottedDict('ROOT', simplejson.loads(json))
99 data = DottedDict('ROOT', safer_eval(json))
102 if rsp.stat == 'fail':
103 raise RTMAPIError, 'API call failed - %s (%s)' % (
104 rsp.err.msg, rsp.err.code)
108 def getNewFrob(self):
109 rsp = self.get(method='rtm.auth.getFrob')
110 self._authInfo.dataReceived('frob', rsp.frob)
113 def getAuthURL(self):
115 frob = self._authInfo.get('frob')
116 except AuthStateMachine.NoData:
117 frob = self.getNewFrob()
120 'api_key': self._apiKey,
124 params['api_sig'] = self._sign(params)
125 return AUTH_SERVICE_URL + '?' + urllib.urlencode(params)
128 frob = self._authInfo.get('frob')
129 rsp = self.get(method='rtm.auth.getToken', frob=frob)
130 self._authInfo.dataReceived('token', rsp.auth.token)
131 return rsp.auth.token
134 class RTMAPICategory(object):
135 "See the `API` structure and `RTM.__init__`"
137 def __init__(self, rtm, prefix, methods):
138 self._rtm = weakref.ref(rtm)
139 self._prefix = prefix
140 self._methods = methods
142 def __getattr__(self, attr):
143 if attr not in self._methods:
144 raise AttributeError, 'No such attribute: %s' % attr
146 rargs, oargs = self._methods[attr]
147 if self._prefix == 'tasksNotes':
148 aname = 'rtm.tasks.notes.%s' % attr
150 aname = 'rtm.%s.%s' % (self._prefix, attr)
151 return lambda **params: self.callMethod(
152 aname, rargs, oargs, **params
155 def callMethod(self, aname, rargs, oargs, **params):
157 for requiredArg in rargs:
158 if requiredArg not in params:
159 raise TypeError, 'Required parameter (%s) missing' % requiredArg
162 if param not in rargs + oargs:
163 warnings.warn('Invalid parameter (%s)' % param)
165 return self._rtm().get(method=aname,
166 auth_token=self._rtm()._authInfo.get('token'),
170 def sortedItems(dictionary):
171 "Return a list of (key, value) sorted based on keys"
172 keys = dictionary.keys()
175 yield key, dictionary[key]
178 class DottedDict(object):
179 "Make dictionary items accessible via the object-dot notation."
181 def __init__(self, name, dictionary):
184 if isinstance(dictionary, dict):
185 for key, value in dictionary.items():
186 if isinstance(value, dict):
187 value = DottedDict(key, value)
188 elif isinstance(value, (list, tuple)):
189 value = [DottedDict('%s_%d' % (key, i), item)
190 for i, item in enumerate(value)]
191 setattr(self, key, value)
194 children = [c for c in dir(self) if not c.startswith('_')]
195 return '<dotted %s: %s>' % (
200 children = [(c, getattr(self, c)) for c in dir(self) if not c.startswith('_')]
201 return '{dotted %s: %s}' % (
204 ('%s: "%s"' % (k, str(v)))
205 for (k, v) in children)
209 def safer_eval(string):
210 return eval(string, {}, {})
216 [('auth_token'), ()],
224 [('timeline', 'contact'), ()],
226 [('timeline', 'contact_id'), ()],
232 [('timeline', 'group'), ()],
234 [('timeline', 'group_id', 'contact_id'), ()],
236 [('timeline', 'group_id'), ()],
240 [('timeline', 'group_id', 'contact_id'), ()],
244 [('timeline', 'name'), ('filter'), ()],
246 [('timeline', 'list_id'), ()],
248 [('timeline', 'list_id'), ()],
252 [('timeline'), ('list_id'), ()],
254 [('timeline', 'list_id', 'name'), ()],
256 [('timeline'), ('list_id'), ()],
264 [('methodName',), ()],
274 [('timeline', 'name',), ('list_id', 'parse',)],
276 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'tags'),
279 [('timeline', 'list_id', 'taskseries_id', 'task_id',), ()],
281 [('timeline', 'list_id', 'taskseries_id', 'task_id'), ()],
284 ('list_id', 'filter', 'last_sync')],
286 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'direction'),
289 [('timeline', 'from_list_id', 'to_list_id', 'taskseries_id', 'task_id'),
292 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
295 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'tags'),
298 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
299 ('due', 'has_due_time', 'parse')],
301 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
304 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
307 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'name'),
310 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
313 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
316 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
319 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
322 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
327 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'note_title', 'note_text'), ()],
329 [('timeline', 'note_id'), ()],
331 [('timeline', 'note_id', 'note_title', 'note_text'), ()],
341 [('to_timezone',), ('from_timezone', 'to_timezone', 'time')],
343 [('text',), ('timezone', 'dateformat')],
355 [('timeline', 'transaction_id'), ()],