(Python)将图像上传到twitter(https://api.twitter.com/1.1/statuses/update.json),请求返回400响应

时间:2017-07-14 12:04:27

标签: python twitter python-requests

img_url = 'https://upload.twitter.com/1.1/media/upload.json'
auth = OAuth1('',
              '',
              '',
              '')

file = open('test.png', 'rb')
binary_data = file.read()
file.close()

img_data = requests.post(img_url, auth = auth, params = {'media': binary_data})
print(img_data)

返回

Response [400]

请注意,通过https://api.twitter.com/1.1/statuses/update.json发布正常文本状态更新工作正常,因此我认为错误请求不在于授权。我还尝试在base 64中对图像进行编码,然后将其传递给'media_data'参数,该参数也返回相同的响应。
到目前为止,我一直在关注https://dev.twitter.com/rest/reference/post/media/upload

上的官方api参考

1 个答案:

答案 0 :(得分:0)

upload_media.py
#!/usr/bin/env python
# coding: utf-8

import json
from requests_oauthlib import OAuth1Session

CK = 'XXXXXXXXXXXXXXXXXXXXXX'                             # Consumer Key
CS = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'         # Consumer Secret
AT = 'XXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # Access Token
AS = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'         # Accesss Token Secert

url_media = "https://upload.twitter.com/1.1/media/upload.json"
url_text = "https://api.twitter.com/1.1/statuses/update.json"

twitter = OAuth1Session(CK, CS, AT, AS)

files = {"media" : open('image.jpg', 'rb')}
req_media = twitter.post(url_media, files = files)

if req_media.status_code != 200:
    print ("image app fail: %s", req_media.text)
    exit()

media_id = json.loads(req_media.text)['media_id']
print ("Media ID: %d" % media_id)

params = {'status': 'image test', "media_ids": [media_id]}
req_media = twitter.post(url_text, params = params)

if req_media.status_code != 200:
    print ("text app fail: %s", req_text.text)
    exit()

print ("OK")

您可以这样做!