Twython - How to update status with media url

三世轮回 提交于 2019-12-07 17:13:59

问题


In my app, I let users to post to twitter. Now i would like to let them update their status with media.

In twython.py i see a method update_status_with_media that reads the image from filesystem and uploads to twitter. My images are not in filesystem but on S3 bucket.

How to make this work with S3 bucket urls?

Passing the url in file_ variable, fails on IO Error, no such file or directory.

Passing StringIO fails on UnicodeDecode Error.

Passing urllib.urlopen(url).read() gives file() argument 1 must be encoded string without NULL bytes, not str.

I also tried using post method and got 403 Forbidden from twitter api, Error creating status.

Just Solved it

Bah, just got it to work, finally! Maybe it will help someone else to save a few hours it cost me.

twitter = Twython(
        app_key=settings.TWITTER_CONSUMER_KEY, app_secret=settings.TWITTER_CONSUMER_SECRET,
        oauth_token=token.token, oauth_token_secret=token.secret
    )
img = requests.get(url=image_obj.url).content
tweet = twitter.post('statuses/update_with_media',
                                 params={'status': msg},
                                 files={'media': (image_obj.url,
                                                  BytesIO(img))})

回答1:


Glad to see you found an answer! There's a similar problem that we handled recently in a repo issue - basically, you can do the following with StringIO and passing it directly to twitter.post like you did:

from StringIO import StringIO
from twython import Twython

t = Twython(...)
img = open('img_url').read()
t.post('/statuses/update_with_media', params = {'status': 'Testing New Status'}, files = {
    'media': StringIO(img)
    # 'media': ('OrThisIfYouWantToNameTheFile.lol', StringIO(img))
})

This isn't a direct answer to your question, so I'm not expecting any vote or anything, but figured it's seemingly useful to some people and somewhat related so I'd drop a note.



来源:https://stackoverflow.com/questions/16518689/twython-how-to-update-status-with-media-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!