2012-08-06 67 views
0

我想在python中创建泛型类,它将执行所有oAuth过程,然后将允许从任何oAuth支持服务(例如Twitter,LinkedIn)检索数据。无法从Twitter使用access_token检索认证数据

编辑: 我有客户密钥和密码并访问令牌密钥和密码,当我试图要求任何资源请求我收到以下错误: {"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.' 

回答

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

1

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

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

+0

不,它不工作,将只会工作。另外,我编辑了这个问题,并简化了代码 – zohar 2012-08-07 06:09:28