Skip to content

Instantly share code, notes, and snippets.

@terrycojones
Created March 31, 2012 16:30
Show Gist options
  • Save terrycojones/2266563 to your computer and use it in GitHub Desktop.
Save terrycojones/2266563 to your computer and use it in GitHub Desktop.
from json import loads
from oauth2 import Client, Consumer, Token
from urllib import urlencode
class TumblrError(Exception):
"""Hold information about an error from the Tumblr API.
@param url: The C{str} URL that the API call used.
@param status: The C{int} HTTP status returned in the error.
@param message: The C{str} The error message from Tumblr, if any,
else C{None}.
"""
def __init__(self, url, status, message=None):
self._url = url
self._status = status
self._message = message
def __str__(self):
return '<%s: status=%s url=%s%s>' % (
self.__class__.__name__, self._status, self._url,
('message=' + self._message) if self._message else '')
class TumblrClient(object):
"""Facilitate calls to the Tumblr OAuth2 API.
See docs at http://www.tumblr.com/docs/en/api/v2
@param consumerKey: the C{str} the consumer application's key.
@param consumerSecret: the C{str} consumer's secret.
@param oauthToken: the C{str} OAuth token for the user.
@param oauthTokenSecret: the C{str} OAuth token secret for the user.
"""
baseURL = 'http://api.tumblr.com/v2/'
def __init__(self, consumerKey, consumerSecret, oauthToken,
oauthTokenSecret):
consumer = Consumer(consumerKey, consumerSecret)
token = Token(oauthToken, oauthTokenSecret)
self.client = Client(consumer, token)
self._consumerKey = consumerKey
def _request(self, url, method):
"""Make a request to the Tumblr API.
@param url: the C{str} URL to call to (we prefix this with
self.baseURL).
@param method: the C{str} HTTP method to use.
@return: A C{dict} made from the JSON object in the Tumblr response.
@raise TumblrError: if Tumblr returns a error status.
"""
url = self.baseURL + url
response, content = self.client.request(url, method)
status = int(response['status'])
if status < 200 or status >= 300:
raise TumblrError(url, status)
content = loads(content)
meta = content['meta']
if meta['status'] != 200:
raise TumblrError(url, meta['status'], message=meta['msg'])
return content['response']
def getUser(self):
"""Get information about a user's Tumblr blogs.
@return: A C{dict} of user blog information from the JSON in the Tumblr
response. See http://www.tumblr.com/docs/en/api/v2#user-methods
@raise TumblrError: if Tumblr returns a error status.
"""
return self._request('user/info', 'POST')
def getPosts(self, blogURL, params=None):
"""Retrieve a set of posts from a user's Tumblr blog.
@param blogURL: the C{str} URL of the blog, as found in the 'blogs'
'url' section of the user information returned by L{getUser}.
@param params: a C{dict} of URL parameters for the API call, e.g.,
'offset'.
@return: A C{dict} of blogs entries made from the JSON object in the
Tumblr response. See http://www.tumblr.com/docs/en/api/v2#posts
@raise TumblrError: if Tumblr returns a error status.
"""
blogURL = blogURL.rstrip('/')
if blogURL.startswith('http://'):
blogURL = blogURL[7:]
params = params or {}
params['api_key'] = self._consumerKey
url = 'blog/' + blogURL + '/posts?' + urlencode(params)
return self._request(url, 'GET')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment