-1

我尝试通过 Python 使用 Twitter API。我使用 oauth 库和更新功能。

代码是:

oauth_token    = oauth.Token(key=twitter_settings.access_token_key, secret=twitter_settings.access_token_secret)
oauth_consumer = oauth.Consumer(key=twitter_settings.consumer_key, secret=twitter_settings.consumer_secret)

signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()

http_handler  = urllib.HTTPHandler(debuglevel=_debug)
https_handler = urllib.HTTPSHandler(debuglevel=_debug)

def twitter_req(url, method, parameters):
  req = oauth.Request.from_consumer_and_token(oauth_consumer,
                                             token=oauth_token,
                                             http_method=http_method,
                                             http_url=url, 
                                             parameters=parameters)

  req.sign_request(signature_method_hmac_sha1, oauth_consumer, oauth_token)

  headers = req.to_header()

  if method == "POST":
    encoded_post_data = req.to_postdata()
  else:
    encoded_post_data = None
    url = req.to_url()

  print encoded_post_data
  print url
  opener = urllib.OpenerDirector()
  opener.add_handler(http_handler)
  opener.add_handler(https_handler)

  response = opener.open(url, encoded_post_data)

  return response

update_url = "https://api.twitter.com/1.1/statuses/update.json"
update_parameters = {'status': "test"}    

update_response = twitter_req(update_url, "POST", update_parameters)

我收到此错误:

{"errors":[{"message":"Could not authenticate you","code":32}]}

我花了几个小时试图在互联网上找到答案,但我做不到。请帮忙。

4

1 回答 1

0

您的 OAuth 签名有问题。

注意http_method=methodnot中的变化http_method=http_method

  req = oauth.Request.from_consumer_and_token(oauth_consumer,
                                             token=oauth_token,
                                             http_method=method,
                                             http_url=url, 
                                             parameters=parameters)

您可能还会发现此页面有助于解释错误代码的含义。

于 2013-07-30T00:01:21.493 回答