3 Python library for Remember The Milk API
5 @note For help, see http://www.rememberthemilk.com/services/api/methods/
14 _use_simplejson = False
17 _use_simplejson = True
22 __author__ = 'Sridhar Ratnakumar <http://nearfar.org/>'
24 SERVICE_URL = 'http://api.rememberthemilk.com/services/rest/'
25 AUTH_SERVICE_URL = 'http://www.rememberthemilk.com/services/auth/'
28 class RTMError(StandardError):
32 class RTMAPIError(RTMError):
36 class RTMParseError(RTMError):
40 class AuthStateMachine(object):
41 """If the state is in those setup for the machine, then return
42 the datum sent. Along the way, it is an automatic call if the
46 class NoData(RTMError):
49 def __init__(self, states):
53 def dataReceived(self, state, datum):
54 if state not in self.states:
55 raise RTMError, "Invalid state <%s>" % state
56 self.data[state] = datum
59 if state in self.data:
60 return self.data[state]
62 raise AuthStateMachine.NoData('No data for <%s>' % state)
67 def __init__(self, userID, apiKey, secret, token=None):
71 self._authInfo = AuthStateMachine(['frob', 'token'])
73 # this enables one to do 'rtm.tasks.getList()', for example
74 for prefix, methods in API.items():
76 RTMAPICategory(self, prefix, methods))
79 self._authInfo.dataReceived('token', token)
81 def _sign(self, params):
82 "Sign the parameters with MD5 hash"
83 pairs = ''.join(['%s%s' % (k, v) for (k, v) in sortedItems(params)])
84 return md5(self._secret+pairs).hexdigest()
87 def open_url(url, queryArgs=None):
89 url += '?' + urllib.urlencode(queryArgs)
90 warnings.warn("Performing download of %s" % url, stacklevel=5)
91 return urllib2.urlopen(url)
93 def get(self, **params):
94 "Get the XML response for the passed `params`."
95 params['api_key'] = self._apiKey
96 params['format'] = 'json'
97 params['api_sig'] = self._sign(params)
99 connection = self.open_url(SERVICE_URL, params)
100 json = connection.read()
101 data = DottedDict('ROOT', parse_json(json))
104 if rsp.stat == 'fail':
105 raise RTMAPIError, 'API call failed - %s (%s)' % (
106 rsp.err.msg, rsp.err.code)
110 def getNewFrob(self):
111 rsp = self.get(method='rtm.auth.getFrob')
112 self._authInfo.dataReceived('frob', rsp.frob)
115 def getAuthURL(self):
117 frob = self._authInfo.get('frob')
118 except AuthStateMachine.NoData:
119 frob = self.getNewFrob()
122 'api_key': self._apiKey,
126 params['api_sig'] = self._sign(params)
127 return AUTH_SERVICE_URL + '?' + urllib.urlencode(params)
130 frob = self._authInfo.get('frob')
131 rsp = self.get(method='rtm.auth.getToken', frob=frob)
132 self._authInfo.dataReceived('token', rsp.auth.token)
133 return rsp.auth.token
136 class RTMAPICategory(object):
137 "See the `API` structure and `RTM.__init__`"
139 def __init__(self, rtm, prefix, methods):
140 self._rtm = weakref.ref(rtm)
141 self._prefix = prefix
142 self._methods = methods
144 def __getattr__(self, attr):
145 if attr not in self._methods:
146 raise AttributeError, 'No such attribute: %s' % attr
148 rargs, oargs = self._methods[attr]
149 if self._prefix == 'tasksNotes':
150 aname = 'rtm.tasks.notes.%s' % attr
152 aname = 'rtm.%s.%s' % (self._prefix, attr)
153 return lambda **params: self.callMethod(
154 aname, rargs, oargs, **params
157 def callMethod(self, aname, rargs, oargs, **params):
159 for requiredArg in rargs:
160 if requiredArg not in params:
161 raise TypeError, 'Required parameter (%s) missing' % requiredArg
164 if param not in rargs + oargs:
165 warnings.warn('Invalid parameter (%s)' % param)
167 return self._rtm().get(method=aname,
168 auth_token=self._rtm()._authInfo.get('token'),
172 def sortedItems(dictionary):
173 "Return a list of (key, value) sorted based on keys"
174 keys = dictionary.keys()
177 yield key, dictionary[key]
180 class DottedDict(object):
181 "Make dictionary items accessible via the object-dot notation."
183 def __init__(self, name, dictionary):
186 if isinstance(dictionary, dict):
187 for key, value in dictionary.items():
188 if isinstance(value, dict):
189 value = DottedDict(key, value)
190 elif isinstance(value, (list, tuple)):
191 value = [DottedDict('%s_%d' % (key, i), item)
192 for i, item in enumerate(value)]
193 setattr(self, key, value)
196 children = [c for c in dir(self) if not c.startswith('_')]
197 return '<dotted %s: %s>' % (
202 children = [(c, getattr(self, c)) for c in dir(self) if not c.startswith('_')]
203 return '{dotted %s: %s}' % (
206 ('%s: "%s"' % (k, str(v)))
207 for (k, v) in children)
211 def safer_eval(string):
213 return eval(string, {}, {})
214 except SyntaxError, e:
218 newE = RTMParseError("Error parseing json")
224 parse_json = simplejson.loads
226 parse_json = safer_eval
232 [('auth_token'), ()],
240 [('timeline', 'contact'), ()],
242 [('timeline', 'contact_id'), ()],
248 [('timeline', 'group'), ()],
250 [('timeline', 'group_id', 'contact_id'), ()],
252 [('timeline', 'group_id'), ()],
256 [('timeline', 'group_id', 'contact_id'), ()],
260 [('timeline', 'name'), ('filter'), ()],
262 [('timeline', 'list_id'), ()],
264 [('timeline', 'list_id'), ()],
268 [('timeline'), ('list_id'), ()],
270 [('timeline', 'list_id', 'name'), ()],
272 [('timeline'), ('list_id'), ()],
280 [('methodName',), ()],
290 [('timeline', 'name',), ('list_id', 'parse',)],
292 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'tags'),
295 [('timeline', 'list_id', 'taskseries_id', 'task_id',), ()],
297 [('timeline', 'list_id', 'taskseries_id', 'task_id'), ()],
300 ('list_id', 'filter', 'last_sync')],
302 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'direction'),
305 [('timeline', 'from_list_id', 'to_list_id', 'taskseries_id', 'task_id'),
308 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
311 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'tags'),
314 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
315 ('due', 'has_due_time', 'parse')],
317 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
320 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
323 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'name'),
326 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
329 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
332 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
335 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
338 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
343 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'note_title', 'note_text'), ()],
345 [('timeline', 'note_id'), ()],
347 [('timeline', 'note_id', 'note_title', 'note_text'), ()],
357 [('to_timezone',), ('from_timezone', 'to_timezone', 'time')],
359 [('text',), ('timezone', 'dateformat')],
371 [('timeline', 'transaction_id'), ()],