Search code examples
pythonblogsimagetumblr

Post picture from directory to tumblr via python


I searched the boards and found a thread to which I used to make a script to upload a picture to tumblr.

from tumblr import Api
import sys

def antearaTumblr(blog, email, password):
    BLOG=blog
    USER=email
    PASSWORD=password
    api = Api(BLOG,USER,PASSWORD)
    #data = open('C:/Users/Kevin/Desktop/python-tumblr-0.1/1329360987775.jpg').read()
    api.write_photo('http://www.jonathanworthington.co.uk/wp-content/uploads/2008/07/etc.jpg')
    title = ''
    body = ''
    api.write_regular(title,body)

This does work, it uses write_photo to grab a photo from the internet and upload it to my tumblr. However, I don't know how to make it grab a photo from a directory on my PC, like this....

from tumblr import Api
import sys

def antearaTumblr(blog, email, password):
    BLOG=blog
    USER=email
    PASSWORD=password
    api = Api(BLOG,USER,PASSWORD)
    data = open('C:/Users/Kevin/Desktop/python-tumblr-0.1/1329360987775.jpg').read()
    title = ''
    body = ''
    api.write_regular(title,data)

It succeeds in uploading, however all it uploads is this... ÿØÿà... which I assume is the jpg header.

I found this topic Post picture to Tumblr using Python but I don't know exactly what the replies are saying.

Does anyone know how to get it to work using a directory and not a link?

Also, i tried this https://gist.github.com/1242662 but honestly I just had no idea how to do it.

Thanks for any help I receive.


Solution

  • Looking at the linked post it seems that data is a keyword argument, so you'd call api.write like this:

    api.write_regular(title, data=data)
    

    I have no idea if that will work or not, but tumblr's API seems well documented. I would recommend using requests instead, which is by far the nicest HTTP library for Python. To upload a photo:

    import requests
    
    url = 'https://www.tumblr.com/api/write'
    data = {'email': your_email, 'password': your_password, 'type': 'photo'}
    files = {'data': open('your_image.jpg')}
    
    requests.post(url, data=data, files=files)