A Python Library to interface with Tumblr v2 REST API & OAuth

Overview

Tumblpy

https://pypip.in/d/python-tumblpy/badge.png

Tumblpy is a Python library to help interface with Tumblr v2 REST API & OAuth

Features

  • Retrieve user information and blog information
  • Common Tumblr methods
    • Posting blog posts
    • Unfollowing/following blogs
    • Edit/delete/reblog posts
    • And many more!!
  • Photo Uploading
  • Transparent Python 3 Support!

Installation

Installing Tumbply is simple:

$ pip install python-tumblpy

Usage

Importing

from tumblpy import Tumblpy

Authorization URL

t = Tumblpy(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET)

auth_props = t.get_authentication_tokens(callback_url='http://michaelhelmick.com')
auth_url = auth_props['auth_url']

OAUTH_TOKEN_SECRET = auth_props['oauth_token_secret']

print 'Connect with Tumblr via: %s' % auth_url

Once you click "Allow" be sure that there is a URL set up to handle getting finalized tokens and possibly adding them to your database to use their information at a later date.

Handling the Callback

# OAUTH_TOKEN_SECRET comes from the previous step
# if needed, store those in a session variable or something

# oauth_verifier and OAUTH_TOKEN are found in your callback url querystring
# In Django, you'd do something like
# OAUTH_TOKEN = request.GET.get('oauth_token')
# oauth_verifier = request.GET.get('oauth_verifier')


t = Tumblpy(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET,
            OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

authorized_tokens = t.get_authorized_tokens(oauth_verifier)

final_oauth_token = authorized_tokens['oauth_token']
final_oauth_token_secret = authorized_tokens['oauth_token_secret']

# Save those tokens to the database for a later use?

Getting some User information

# Get the final tokens from the database or wherever you have them stored

t = Tumblpy(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET,
            OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

# Print out the user info, let's get the first blog url...
blog_url = t.post('user/info')
blog_url = blog_url['user']['blogs'][0]['url']

Getting posts from a certain blog

# Assume you are using the blog_url and Tumblpy instance from the previous section
posts = t.get('posts', blog_url=blog_url)
print posts
# or you could use the `posts` method
audio_posts = t.posts(blog_url, 'audio')
print audio_posts
all_posts = t.posts(blog_url)
print all_posts

Creating a post with a photo

# Assume you are using the blog_url and Tumblpy instance from the previous sections

photo = open('/path/to/file/image.png', 'rb')
post = t.post('post', blog_url=blog_url, params={'type':'photo', 'caption': 'Test Caption', 'data': photo})
print post  # returns id if posted successfully

Posting an Edited Photo (This example resizes a photo)

# Assume you are using the blog_url and Tumblpy instance from the previous sections

# Like I said in the previous section, you can pass any object that has a
# read() method

# Assume you are working with a JPEG

from PIL import Image
from StringIO import StringIO

photo = Image.open('/path/to/file/image.jpg')

basewidth = 320
wpercent = (basewidth / float(photo.size[0]))
height = int((float(photo.size[1]) * float(wpercent)))
photo = photo.resize((basewidth, height), Image.ANTIALIAS)

image_io = StringIO.StringIO()
photo.save(image_io, format='JPEG')

image_io.seek(0)

try:
    post = t.post('post', blog_url=blog_url, params={'type':'photo', 'caption': 'Test Caption', 'data': photo})
    print post
except TumblpyError, e:
    # Maybe the file was invalid?
    print e.message

Following a user

# Assume you are using the blog_url and Tumblpy instance from the previous sections
try:
    follow = t.post('user/follow', params={'url': 'tumblpy.tumblr.com'})
except TumblpyError:
    # if the url given in params is not valid,
    # Tumblr will respond with a 404 and Tumblpy will raise a TumblpyError

Get a User Avatar URL (No need for authentication for this method)

t = Tumblpy()
avatar = t.get_avatar_url(blog_url='tumblpy.tumblr.com', size=128)
print avatar['url']

# OR

avatar = t.get('avatar', blog_url='tumblpy.tumblr.com', extra_endpoints=['128'])
print avatar['url']

Catching errors

try:
    t.post('user/info')
except TumbplyError, e:
    print e.message
    print 'Something bad happened :('

Thanks for using Tumblpy!

Comments
  • 0.6.1

    0.6.1

    This changes a few things:

    • Allows for numbers and boolean params to be sent to Tumblr's API.
      • Examples: Under /posts, limit is a Number and reblog_info is a Boolean.
    • Include default_params consisting of the api_key, like before. If not, /posts requests don't work.
    • In the event that the api_key that is sent in the params is wrong/expired, throw an AuthError.
    • Allow the user to manipulate urllib3's maxsize via request's pool_maxsize for multi-threaded applications.
    • Updated t.get_access_token to t.get_authorized_tokens in the README.
    opened by joaquincasares 20
  • Handle empty/ 404 responses

    Handle empty/ 404 responses

    The Tumblr API returns and empty list (and not a dict) in some cases, e. g. if a blog was not found (404). In these case, calling content.get() raises an AttributeError. This commit fixes it.

    Example for a 404 response: http://api.tumblr.com/v2/blog/cocofuckedchanel.tumblr.com/posts/

    opened by mkai 18
  • oauth issue

    oauth issue

    tried to use your python package but got below error...how can i fix this issue?

    Traceback (most recent call last): File "test.py", line 4, in auth_props = t.get_authentication_tokens(callback_url='http://www.xyz.com/somecallbackurl/index.php') File "/opt/.softroot/python-tumblpy/tumblpy/api.py", line 61, in get_authentication_tokens raise TumblpyAuthError('Seems something couldn't be verified with your OAuth junk. Error: %s, Message: %s' % (response.status_code, response.content)) tumblpy.exceptions.TumblpyAuthError: Seems something couldn't be verified with your OAuth junk. Error: 401, Message: oauth_timestamp is too far away; we believe it is now 1390665118, you sent 1390643508, 21610 seconds away

    opened by srinivasuk 8
  • fixed problem with post requests

    fixed problem with post requests

    Post requests didn't include the type parameter, so they would fail. For instance, the example in the readme for posting an image didn't work.

    I'm not sure if this is the best way to solve the problem, but it makes it so I can submit post requests to the api.

    opened by royhodgman 8
  • Posting to secondary blog

    Posting to secondary blog

    Is it possible to use this library to post something to secondary blog?

    I authorized the app and I took a look at Tumblr console where I picked up all the keys from. I have noticed that I can successfully post to my primary blog, but not on secondary (getting {TumblpyError} 404 'There was an error making your request.' error all the time).

    This is my current code:

    from tumblpy import Tumblpy
    
    
    def post_tumblr(
            url,
            comment='',
            tags='',
            **kwargs
    ):
        t = Tumblpy(
            APP_KEY, APP_SECRET,
            OAUTH_TOKEN, OAUTH_TOKEN_SECRET
        )
    
        blog_url = t.post('user/info')
        blog_url = blog_url['user']['blogs'][0]['url']  # POSTING TO PRIMARY BLOG WORKS
        # blog_url = blog_url['user']['blogs'][1]['url']  # CANNOT POST TO SECONDARY BLOG?
    
        post_url = t.post(
            'post',
            blog_url=blog_url,
            params={
                'type': 'video',
                'embed': url,
                'caption': comment,
                'tags': tags,
            }
        )
    
        return True
    
    opened by bomb-on 7
  • Posting error while posting Images.

    Posting error while posting Images.

    'Error: 401, Message: {"meta":{"status":401,"msg":"Not Authorized"},"response":[]}' while posting an image using "data" parameter. I followed your example and that's the error I got. Is this a bug?

    opened by satya10x 7
  • Error 401

    Error 401

    I'm getting the next error everytime I try to post something:

    File "C:\Python27\lib\site-packages\tumblpy.py", line 259, in post extra_endpoints=extra_endpoints, params=params) File "C:\Python27\lib\site-packages\tumblpy.py", line 222, in request raise TumblpyAuthError('Error: %s, Message: %s' % (response.status_code, response.content)) tumblpy.TumblpyAuthError: 'Error: 401, Message: {"meta":{"status":401,"msg":"Not Authorized"},"response":[]}'

    I don't know if is from my code or if is from the library.

    opened by jupazave 7
  • Error making post

    Error making post

    Hello,

    Trying to use the post method for a text post.

    t = Tumblpy(TUMBLR_CONSUMER_KEY, TUMBLR_CONSUMER_SECRET,
                TUMBLR_ACCESS_KEY, TUMBLR_ACCESS_SECRET)
    
            blog_url = t.post('user/info')
            blog_url = blog_url['user']['blogs'][0]['url']
            blog_url = blog_url.replace('http://', '')
            blog_url = blog_url.replace('/', '')
            print(blog_url)
    
            try:
                if image:
                    #Create a photo post using a local filepath
                    post = t.post('post', blog_url=blog_url, params={'type':'photo', 'caption': text, 'data': image})
                elif url:
                    #Create a link post
                    post = t.post('post', blog_url=blog_url, params={'type':'link', 'url': url, 'description': text})
                else:
                    print('im definitely text')
                    #Create a text post
                    post = t.post('post', blog_url=blog_url, params={'type':'text', 'body': text})
            except Exception as e:
                import pdb; pdb.set_trace()
                print(e)
    
            return HttpResponse(status=200)
    

    The text is just a normal string. I'm using Pythin 3.4.

    Error is tumblpy.exceptions.TumblpyError: There was an error making your request. and error_code is 404

    Any ideas why this isn't working? Thanks!

    opened by amanthei 6
  • Fully Converting over to requests_oauthlib

    Fully Converting over to requests_oauthlib

    Everything seems to be working now, though lacking tests, it's hard to know specifically if it's working, but it's working for my follower tracker that I'm working on.

    opened by graysonarts 5
  • Can't Reblog Posts

    Can't Reblog Posts

    Using the following:

    t.post('post/reblog', params={'id':someid,'reblog_key':somereblog_key})
    

    I get:

    Invalid ID or reblog_key specified
    

    I have double checked the reblog key on the post and the id, these are correct, however no matter what I do I get that result, I even built my own module to reblog posts in request_oauthlib!

    opened by agieocean 4
  • Decode fix

    Decode fix

    Fix issues with GET requests in get_authentication_tokens and get_authorized_tokens returns value in bytes and needed to be decoded before response data can be worked with.

    The response.content would return an dict with the keys and values encoded;

    {b'oauth_token': b'Yh...token...EQ', b'oauth_token_secret': b'YH...token...gO', b'oauth_callback_confirmed': b'true'}
    
    opened by wmantly 4
  • Tumblr can return error responses that aren't handled correctly

    Tumblr can return error responses that aren't handled correctly

    It appears that when Tumblr is having issues, error responses can be different than expected.

    I got the error: AttributeError: 'str' object has no attribute 'get'

    Sentry recorded that content was a str instead of a dict. The status code was 504.

    Relevant line: https://github.com/michaelhelmick/python-tumblpy/blob/master/tumblpy/api.py#L165

    It seems like the easiest fix would be to check if the response was a str and if it was, use that for the error_message. Also, in looking at that code, it appears error_message gets written over for every error instead of being appended to. This seems like it could be fixed by ', '.join(content['errors']) instead of the loop.

    If these seems like reasonable fixes, I'm happy to open a PR for them.

    opened by Syfaro 2
Releases(1.1.4)
Owner
Mike Helmick
Mike Helmick
A Python Tumblr API v2 Client

PyTumblr Installation Install via pip: $ pip install pytumblr Install from source: $ git clone https://github.com/tumblr/pytumblr.git $ cd pytumblr $

Tumblr 677 Dec 21, 2022
A Python Library to interface with LinkedIn API, OAuth and JSON responses

#Overview Here's another library based on the LinkedIn API, OAuth and JSON responses. Hope this documentation explains everything you need to get star

Mike Helmick 69 Dec 11, 2022
Python bindings to the Syncthing REST interface.

python-syncthing Python bindings to the Syncthing REST interface. Python API Documentation Syncthing Syncthing REST Documentation Syncthing Forums $ p

Blake VandeMerwe 64 Aug 13, 2022
Python library for interacting with the Wunderlist 2 REST API

Overview Wunderpy2 is a thin Python library for accessing the official Wunderlist 2 API. What does a thin library mean here? Only the bare minimum of

mieubrisse 24 Dec 29, 2020
NiceHash Python Library and Command Line Rest API

NiceHash Python Library and Command Line Rest API Requirements / Modules pip install requests Required data and where to get it Following data is nee

Ashlin Darius Govindasamy 2 Jan 2, 2022
NiceHash Python Library and Command Line Rest API

NiceHash Python Library and Command Line Rest API Requirements / Modules pip install requests Required data and where to get it Following data is nee

Ashlin Darius Govindasamy 2 Jan 2, 2022
TM1py is a Python package that wraps the TM1 REST API in a simple to use library.

By wrapping the IBM Planning Analytics (TM1) REST API in a concise Python framework, TM1py facilitates Python developments for TM1. Interacting with T

Cubewise CODE 147 Dec 15, 2022
Python library wrapping and enhancing the Invenio RDM REST API.

Iridium The metal Iridium is used to refine and enhance metal alloys. Similarly, this package provides an enhanced coating around the Invenio RDM APIs

Materials Data Science and Informatics 2 Mar 29, 2022
A client library for the REST API of DocuWare's DMS

docuware-client This is a client library for the REST API of DocuWare DMS. Since DocuWare's documentation regarding the REST API is very sparse (at th

Stefan Schönberger 1 Feb 23, 2022
A very simple Salesforce.com REST API client for Python

Simple Salesforce Simple Salesforce is a basic Salesforce.com REST API client built for Python 3.5, 3.6, 3.7 and 3.8. The goal is to provide a very lo

simple salesforce 1.4k Dec 29, 2022
📦 Opensource Python wrapper for Hiven's REST and WebSocket API

hiven.py ?? Opensource Python wrapper for Hiven's REST and WebSocket API Installation pip install -U hiven.py Usage hiven.py is currently under devel

Kevin Thomas 3 Sep 3, 2021
Python bindings for swm-core client REST API

Python bindings for swm-core client REST API Description Sky Port is an universal bus between user software and compute resources. It can also be cons

Sky Workflows 1 Jan 1, 2022
An unofficial Python wrapper for the 'Binance exchange REST API'

Welcome to binex_f v0.1.0 many interfaces are heavily used by myself in product environment, the websocket is reliable (re)connected. Latest version:

DeepLn 2 Jan 5, 2022
pyDuinoCoin is a simple python integration for the DuinoCoin REST API, that allows developers to communicate with DuinoCoin Master Server

PyDuinoCoin PyDuinoCoin is a simple python integration for the DuinoCoin REST API, that allows developers to communicate with DuinoCoin Main Server. I

BackrndSource 6 Jul 14, 2022
HTTP Calls to Amazon Web Services Rest API for IoT Core Shadow Actions 💻🌐💡

aws-iot-shadow-rest-api HTTP Calls to Amazon Web Services Rest API for IoT Core Shadow Actions ?? ?? ?? This simple script implements the following aw

AIIIXIII 3 Jun 6, 2022
Jackrabbit Relay is an API endpoint for stock, forex and cryptocurrency exchanges that accept REST webhooks.

JackrabbitRelay Jackrabbit Relay is an API endpoint for stock, forex and cryptocurrency exchanges that accept REST webhooks. Disclaimer Please note RA

Rose Heart 23 Jan 4, 2023
Python3 based bittrex rest api wrapper

bittrex-rest-api This open source project was created to give an understanding of the Bittrex Rest API v1.1/v3.0 in pearl language. The sample file sh

null 4 Nov 15, 2022
Spore REST API asyncio client

Spore REST API asyncio client

LEv145 16 Aug 2, 2022
Source code for Profile REST API

PROJECT PROFILE REST API Creating local development server: We will create a local development server that can run and test our API as we build it. We

null 1 Mar 29, 2022