0
from rauth.service import OAuth1Service

class TwitterClient:

    KNOWN_USERS = ['177512438-pJTdMgOPLJ8hCQFfDbPmkU3LRcCSHZd5VqoM3WaY', '7Z50XjV1CqDF1753Rzd4MkzSYN1oCY2FaaFtAZU']

    def __init__(self):
        # Get a real consumer key & secret from https://dev.twitter.com/apps/new
        self.twitter = OAuth1Service(
            name='twitter',
            consumer_key='ZjXNoqpLfhQvYBgkjrrvxQ',
            consumer_secret='8O4NjcsNed8uGICjDLNTjPiNwqjPezovWZIVru1c',
            request_token_url='https://api.twitter.com/oauth/request_token',
            access_token_url='https://api.twitter.com/oauth/access_token',
            authorize_url='https://api.twitter.com/oauth/authorize',
            base_url='https://api.twitter.com/1/')
        #self.KNOWN_USERS = ['177512438-pJTdMgOPLJ8hCQFfDbPmkU3LRcCSHZd5VqoM3WaY', '7Z50XjV1CqDF1753Rzd4MkzSYN1oCY2FaaFtAZU']

    def new_session(self):
        request_token, request_token_secret = self.twitter.get_request_token()
        authorize_url = self.twitter.get_authorize_url(request_token)
        print 'Visit this URL in your browser: ' + authorize_url
        pin = raw_input('Enter PIN from browser: ')
        session = self.twitter.get_auth_session(request_token,
                                                request_token_secret,
                                                method='POST',
                                                data={'oauth_verifier': pin})
        print session.access_token, session.access_token_secret # Save this to database
        return session

    def reuse_session(self, user2):
        access_token = user2[0]
    access_token_secret = user2[1]
        session = self.twitter.get_session((access_token, access_token_secret))
        return session

    def init_session(self, user2):
        if user2[0] == self.KNOWN_USERS[0] and user2[1] == self.KNOWN_USERS[1] : session = self.reuse_session(user2)
        else                        : session = self.new_session()
        return session

    def list_tweets(self, user2):
        session = self.init_session(user2)
        params = {'include_rts': 1,  # Include retweets
                  'count': 10}       # 10 tweets

        r = session.get('statuses/home_timeline.json', params=params)

        for i, tweet in enumerate(r.json(), 1):
            handle = tweet['user']['screen_name'].encode('utf-8')
            text = tweet['text'].encode('utf-8')
            print '{0}. @{1} - {2}'.format(i, handle, text)

    tc = TwitterClient()

    user1 = ['177512438-pJTdMgOPLJ8hCQFfDbPmkU3LRcCSHZd5VqoM3WaY', '7Z50XjV1CqDF1753Rzd4MkzSYN1oCY2FaaFtAZU']
    tc.list_tweets( user1 )

But this gives the following error in line 50:

string indices must be integer

So instead I write this:

from rauth.service import OAuth1Service

class TwitterClient:

    KNOWN_USERS = { # (access_token, access_token_secret)
        'user1' : ('177512438-pJTdMgOPLJ8hCQFfDbPmkU3LRcCSHZd5VqoM3WaY', '7Z50XjV1CqDF1753Rzd4MkzSYN1oCY2FaaFtAZU')
    }

    def __init__(self):
        # Get a real consumer key & secret from https://dev.twitter.com/apps/new
        self.twitter = OAuth1Service(
            name='twitter',
            consumer_key='ZjXNoqpLfhQvYBgkjrrvxQ',
            consumer_secret='8O4NjcsNed8uGICjDLNTjPiNwqjPezovWZIVru1c',
            request_token_url='https://api.twitter.com/oauth/request_token',
            access_token_url='https://api.twitter.com/oauth/access_token',
            authorize_url='https://api.twitter.com/oauth/authorize',
            base_url='https://api.twitter.com/1.1/')

    def new_session(self):
        request_token, request_token_secret = self.twitter.get_request_token()
        authorize_url = self.twitter.get_authorize_url(request_token)
        print 'Visit this URL in your browser: ' + authorize_url
        pin = raw_input('Enter PIN from browser: ')
        session = self.twitter.get_auth_session(request_token,
                                                request_token_secret,
                                                method='POST',
                                                data={'oauth_verifier': pin})
        print session.access_token, session.access_token_secret # Save this to database
        return session

    def reuse_session(self, user1):
        access_token, access_token_secret = self.KNOWN_USERS[user1]
        session = self.twitter.get_session((access_token, access_token_secret))
        return session

    def init_session(self, user1):
        if user1 in self.KNOWN_USERS : session = self.reuse_session(user1)
        else                        : session = self.new_session()
        return session

    def list_tweets(self, user1):
        session = self.reuse_session(user1)
        params = {'include_rts': 1,  # Include retweets
                  'count': 10}       # 10 tweets

        r = session.get('statuses/home_timeline.json', params=params)
    print r.json
        #for i, tweet in enumerate(r.json(), 1):
            #handle = tweet['user']['screen_name'].encode('utf-8')
            #text = tweet['text'].encode('utf-8')
            #print '{0}.  - {2}'.format(i, text)

tc = TwitterClient()

tc.list_tweets('user1')

But I get the following error:

<bound method Response.json of <Response [401]>>
4

1 回答 1

0

根据您提供给我们的最少信息,我猜您的 GET 请求失败,导致您收到如下所示的 JSON 对象:

{"errors":[{"message":"Bad Authentication data","code":215}]}

这将解码为字典,当您对其进行迭代时,您将获得字典中的键,它们是字符串。当您尝试使用字典键对这些字符串进行索引时,您会得到一个错误,即您只能使用整数对字符串(或任何序列)进行索引。

通过在迭代之前打印 r.json() 来验证这一点。通过阅读您收到的错误消息并纠正它向您报告的问题来修复它。

于 2013-07-15T04:07:26.290 回答