使用从tweepy获得的访问令牌时,“代码”:32,“消息”:“无法验证您。”

2024-04-19 18:03:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用twitter的区块上传功能

参考:https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload-init

因为这个特性在tweepy上不可用,所以我尝试从头开始实现它。但是,由于用户已经使用tweepy使用应用程序登录,tweepy保存了从那里获得的用户的访问令牌和密码

我尝试按如下方式使用这些访问令牌,但得到了错误"code":32,"message":"Could not authenticate you."

我想探索一种方式,不会要求用户输入他们的电子邮件和密码再次上传视频

from requests_oauthlib import OAuth1, OAuth1Session
import os

def upload_video(video_file):
  video_file = os.path.join(MEDIA_ROOT, 'test_video.mp4')

  oauth_token = OAUTH_TOKEN
  oauth_token_secret = OAUTH_TOKEN_SECRET

  consumer_key = TWITTER_CONSUMER_TOKEN
  consumer_secret = TWITTER_CONSUMER_TOKEN_SECRET

  oauth = OAuth1Session(consumer_key,
                client_secret=consumer_secret,
                resource_owner_key=oauth_token,
                resource_owner_secret=oauth_token_secret,
                signature_method='HMAC-SHA1')

  headers = requests.utils.default_headers()

  headers.update(
    {
        'User-Agent': 'OAuth gem v0.4.4',
    }
  )

  video_url = 'https://upload.twitter.com/1.1/media/upload.json?command=INIT&total_bytes={size}&media_type={type}'.format(size=os.path.getsize(video_file), type='video/mp4')

  response = oauth.post(video_url,
                         headers=headers,
                         files=dict(foo='bar')) # to make it in multipart/form-data
  print(response.content)
  print(response.request.body)
  print(response.request.headers)  

我还打印了请求标题,如下所示:

{'User-Agent': b'OAuth gem v0.4.4', 'Accept-Encoding': b'gzip, deflate', 'Accept': b'*/*', 'Connection': b'keep-alive', 'Content-Length': '141', 'Content-Type': b'multipart/form-data; boundary=f5c7d61e8ab8a14b2a22ced4171b723e', 
'Authorization': b'OAuth oauth_nonce="147920959083366377161589749583", oauth_timestamp="1589749583", oauth_version="1.0", oauth_signature_method="HMAC-SHA1", oauth_consumer_key="consumer_key", oauth_token="oauth_token", oauth_signature="mcEaLBsANVu%2B7lavaNfrOiHZbgs%3D"'}

我还尝试了twurl命令,该命令确实得到了正确的响应,但它要求我输入用户名和密码,并生成了一组与tweepy不同的oauth_令牌和密码


Tags: key用户token密码secretconsumerresponsevideo