Source

RIL / readitlater / api.py

Full commit
#!/usr/bin/env python2.6
# -*- coding: utf-8 -*-

import logging
import urllib
import urllib2

API_ENDPOINT = 'https://readitlaterlist.com/v2/'

class ReadItLaterError(Exception): pass
class RequestError(ReadItLaterError): pass
class AuthError(ReadItLaterError): pass
class RateLimitExceeded(ReadItLaterError): pass
class ServerError(ReadItLaterError): pass

class API(object):
    def __init__(self, api_key, username=None, password=None):
        self.__status = None
        self.api_key = api_key

    def __call(self, method, **params):
        params['apikey'] = self.api_key
        try:
            res = urllib2.urlopen("%s%s?%s" % (
                API_ENDPOINT, method, urllib.urlencode(params)))
            logging.debug(res.url)
            self.__status = {
                    'User-Limit': res.headers.get('X-Limit-User-Limit'),
                    'User-Remaining': res.headers.get('X-Limit-User-Remaining'),
                    'User-Reset': res.headers.get('X-Limit-User-Reset'),
                    'Key-Limit': res.headers.get('X-Limit-Key-Limit'),
                    'Key-Remaining': res.headers.get('X-Limit-Key-Remaining'),
                    'Key-Reset': res.headers.get('X-Limit-Key-Reset'), }
            logging.debug(self.__status)
            return res.read()
        except urllib2.URLError, e:
            logging.debug(e.url)
            logging.error(e)

            if e.code == 400:
                raise RequestError("Invalid request, please make sure "
                        "you follow the documentation for proper syntax")
            elif e.code == 401:
                raise AuthError("Username and/or password is incorrect")
            elif e.code == 403:
                raise RateLimitExceeded("Rate limit exceeded, please "
                        "wait a little bit before resubmitting")
            elif e.code == 503:
                raise ServerError("Read It Later's sync server is down "
                        "for scheduled maintenance")
            else:
                raise ReadItLaterError("Unknown error occurred while "
                        "requesting readitlater")

    def auth(self, username, password):
        self.__call('auth', username=username, password=password)
        return True

    def add(self, username, password, url, title):
        self.__call('add', username=username, password=password,
                url=url, title=title)

    def status(self):
        if not self.__status:
            self.__call('api')
        return self.__status

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)