Git Product home page Git Product logo

python-tumblpy's Introduction

Tumblpy

image

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!

python-tumblpy's People

Contributors

basilleaf avatar graysonarts avatar jeflopo avatar joaquincasares avatar jupazave avatar knikolienko avatar lindseyb avatar michaelhelmick avatar mkai avatar mklappir avatar telofy avatar terrycojones avatar wmantly avatar zhanglongqi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-tumblpy's Issues

Posting problem

Hi,

I have problem with posting, this code:
posts = t.get('posts', blog_url="http://lapekkk.tumblr.com/")

works fine, but this one:
post = t.post('post', blog_url='http://lapekkk.tumblr.com/', params={'type':'text', 'title': 'Title Caption', 'body': 'Body content'})

return error: Error: 401, Message: {"meta":{"status":401,"msg":"Not Authorized"},"response":[]}

I have the latest versions of tumblpy.

Error 401 when attempting get_authorized_tokens()

I'm trying to get through the initial Oauth dance and get an authorized token to use. However, Tumblr's API keeps returning the following:

oauth_signature [something] does not match expected value [a thing that is, indeed, different]

any idea what could be happening?

Posting Question

How would I go about posting something that isn't an image (text, audio, video, etc)? I don't see that in your tutorial/description.

Edit (Solved): After a bit of studying the Tumblr API, I figured it out.

request() fails if Tumblr returns https:// URL

I'm playing with a new Tumblr blog and using Tumblpy; it took me a bit to find out why it was failing. On my new blog,

the_client.post('user/info')['user']['blogs'][0]['url']

returns a secure HTTP URL; lines 112 and 113 of api.py fail because they're explicitly matching for 'http://'.

Currently, I'm working around it by replacing 'https://' with 'http://' in a wrapper script, which seems to work fine.

[learning] Posting images

Hello

Sorry to write here. No issue with your code, but a question, if I may ask. If it's a bit long, I'm sorry.

I studied your code because I was trying to write my own tumblr API client with python-requests and I'm pretty far with it. I can authenticate and post textual posts. But when I post an image, I get an error saying: "Headers indicate a formencoded body but body was not decodable" and the tumblr API doc is not really helpful.

The tumblr doc says that the image has to be sent in a parameter called "data". With your code, this works fine:

photo = open('image.png', 'rb')
post = t.post('post', blog_url='myblog.tumblr.com', params={'type':'photo', 'data': photo}) 

But when I try similar things with python-requests alone, it doesn't work. So I've checked your code and you seem to be differentiating 'params' and 'files' but I don't understand how.

In the file api.py (lines 123-126), you write:

kwargs = {'data': params, 'files': files, 'allow_redirects': False}
if files:
    kwargs['params'] = params
response = func(url, **kwargs)

I would be very glad if you explain me what is going on here. Because I'm gessing you're doing something with the parameters that I don't understand.

Or maybe there is a way to send images that I've not yet really understood how.

Thanks a lot in advance.

image post results in httplib error

Just upgraded to the new version, and I'm getting an httplib error while trying to post an image (tried PNG and JPG). Is anyone else having this issue? Text posts are working. I'm using the example code:

photo = open('/path/to/image.jpg', 'rb')
post = t.post('post', blog_url=blog_url, params={'type':'photo', 'data': photo})
print post

Here is the error:

Traceback (most recent call last):
File "test.py", line 30, in
post = t.post('post', blog_url=blog_url, params={'type':'photo', 'data': photo})
File "/usr/lib/python2.7/site-packages/tumblpy.py", line 264, in post
extra_endpoints=extra_endpoints, params=params)
File "/usr/lib/python2.7/site-packages/tumblpy.py", line 218, in request
allow_redirects=False)
File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 330, in post
return self.request('POST', url, data=data, *_kwargs)
File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 269, in request
resp = self.send(prep, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies)
File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 364, in send
r = adapter.send(request, *_kwargs)
File "/usr/lib/python2.7/site-packages/requests/adapters.py", line 152, in send
timeout=timeout,
File "/usr/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 422, in urlopen
body=body, headers=headers)
File "/usr/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 274, in _make_request
conn.request(method, url, **httplib_request_kw)
File "/usr/lib/python2.7/httplib.py", line 958, in request
self._send_request(method, url, body, headers)
File "/usr/lib/python2.7/httplib.py", line 992, in _send_request
self.endheaders(body)
File "/usr/lib/python2.7/httplib.py", line 954, in endheaders
self._send_output(message_body)
File "/usr/lib/python2.7/httplib.py", line 812, in _send_output
msg += message_body
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 400: ordinal not in range(128)

Python3 error on __repr__(self)

Hello

Here's an error I get when running the library with Python 3.2.3

    return u'<TumblrAPI: %s>' % self.app_key
                            ^
SyntaxError: invalid syntax

I can solve it by removing the 'u' in front of '<TumblrAPI: %s>', but not sure if that's the way to go. Or why is it throwing an error in the first place.

Tumblr tags not posting

I am trying to post a post with more than one tag. I can get one to work, but not two.

post = client.post('post', blog_url=blog_url, params={
    'type':'text',
    'state':'published',
    'tags':['test', 'moretests'],
    'body':'test'
    }
                   )

I got one to work by not adding square brackets. I would think I'd use them to use more than one because the Tumblr API uses them, but that doesn't work

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?

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

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!

NameError: name 'urlparse' is not defined

Using Python 3.5 and Python 2.7 with python-tumblpy 1.1.2 I'm getting the following error:

File "/home/myusername/Projects/myproject/env/lib/python3.5/site-packages/tumblpy/api.py", line 185, in post
extra_endpoints=extra_endpoints, params=params)
File ""/home/myusername/Projects/myproject/env/lib/python3.5/site-packages/tumblpy/api.py", line 111, in request
blog_url = urlparse(blog_url)
NameError: name 'urlparse' is not defined

When I did a search through api.py I did only find one reference to urlparse, and that was in the request function. I wasn't able to find an import statement. However, looking further I found the import references.

Changing from .compat import json, urlencode, parse_qsl to from .compat import json, urlencode, parse_qsl, urlparse seemed to clear this error, though now I'm working through figuring out an unauthorized response back from Tumblr. So I'm not entirely sure yet this fixes everything, which is why I haven't submitted a pull request for what could be a simple fix.

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.

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.

Getting value error on basic initializing code

Hi, when I try to run this basic code, I get this error:
ValueError: Only unicode objects are escapable. Got <generator object at 0x1056301e0> of type <type 'generator'>.

What could be the issue? My code is below:

from tumblpy import Tumblpy
from secrets import tumblr_oauth_key , tumblr_secret_key, tumblr_token, tumblr_token_secret

t = Tumblpy(tumblr_token, tumblr_token_secret, tumblr_oauth_key, tumblr_secret_key)
blog_url = t.post('user/info')

urllib2 error when posting stuff

Hey,

i can use your lib to read my postings but when i try to post stuff i will get the following exception:

any ideas ?

Traceback (most recent call last):
File "C:\Users\CeMPUTER\Desktop\python-twitter-0.8.2\examples\tumblr.py", line 10, in
post = t.post('post', blog_url="REMOVED.tumblr.com", params={'type':'text', 'title': 'REMOVED' ,'body':'REMOVED'})
File "build\bdist.win32\egg\tumblpy.py", line 320, in post
File "build\bdist.win32\egg\tumblpy.py", line 312, in api_request
File "build\bdist.win32\egg\tumblpy.py", line 80, in init
tumblpy.TumblpyAuthError: 'There was an error making your request.'

best

Edit: found a way to get it working - i created the

oauth_token and oauth_token_secret

with a different lib and everything works now .. strange

Extra Endpoints

The extra endpoints weren't working for me.They were being appended with a slash between each character.

I modified line 113 of api.py and now the extra endpoints appear to be working .

url = '%s/%s' % (url, extra_endpoints)

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

[Feature] Proxies support

What do you think about adding a proxies=None parameter in the signature of Tumblpy class. To let the session() object connect through it ?

File changes in apy.py: fa73c49

It Would be ok ?

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!

Invalid syntax when declaring object

I get an invalid syntax on the comma "," when I try to make t as shown in the explanation. t = Tumblpy(xxxxxx, xxxxx) I'd show a screenshot instead of the x's but it has my token and such in it. Going from your profile you are really busy and I appreciate you making the program in the first place!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.