0

我正在尝试在 python 中创建通用类,它将完成所有 oAuth 过程,然后允许从任何 oAuth 支持服务(例如 Twitter、LinkedIn)中检索数据。

编辑:我有客户密钥和秘密以及访问令牌密钥和秘密,当我尝试请求任何资源请求时,我收到以下错误: {"error":"Could not authenticate with OAuth.","request":"\/1\/statuses\/retweeted_by_me.json}'

知道为什么吗?

我的代码是:

import httplib
import time
import oauth as oauth

# settings for the local test consumer
SERVER = 'api.twitter.com'

RESOURCE_URL = 'https://api.twitter.com/1/statuses/retweeted_by_me.json'

CONSUMER_KEY = 'MY_CUSTOMER_KEY'
CONSUMER_SECRET = 'MY_CUSTOMER_SECRET'
ACCESS_TOKEN_KEY = 'MY_ACCESS_TOKEN_KEY'
ACCESS_TOKEN_SECRET = 'MY_ACCESS_TOKEN_SECRET'

# example client using httplib with headers
class SimpleOAuthClient(oauth.OAuthClient):

    def __init__(self, server):
        self.server = server
        self.connection = httplib.HTTPSConnection(self.server)

    def access_resource(self, oauth_request):
        # via post body
        # -> some protected resources
        self.connection.request(oauth_request.http_method, RESOURCE_URL)
        response = self.connection.getresponse()
        return response.read()

def run_example2():
  print '** OAuth Python Library Example **'
  client = SimpleOAuthClient(SERVER, )
  consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
  signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
  pause()

  # access some protected resources
  print '* Access protected resources ...'
  pause()
  token = oauth.OAuthToken('ACCESS_TOKEN_KEY', 'ACCESS_TOKEN_SECRET')
  oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, token=token, http_method='GET', http_url=RESOURCE_URL)
  oauth_request.sign_request(signature_method_hmac_sha1, consumer, token)
  print 'REQUEST (via post body)'
  print 'parameters: %s' % str(oauth_request.parameters)
  pause()
  params = client.access_resource(oauth_request)
  print 'GOT'
  print 'non-oauth parameters: %s' % params
  pause()


def pause():
    print ''
    time.sleep(1)

if __name__ == '__main__':
    run_example2()
    print 'Done.'
4

2 回答 2

1

AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authenticate'

这是用于 OAuth 的错误 URL。如果您查看 Twitter 的3-legged OAuth 文档,他们会声明“使用 GET oauth/authorize 端点而不是 /oauth/authenticate”。将 URL 更改为“https://api.twitter.com/oauth/authorize”,然后重试。

于 2012-08-06T17:39:24.497 回答
0

我设法通过更改为来修复self.connection.request(oauth_request.http_method, RESOURCE_URL)self.connection.request(oauth_request.http_method, oauth_request.to_url())

请注意,仅当 oauth_request.http_method 为 GET 时才会起作用

于 2012-08-07T10:23:05.833 回答