3

您好,我是 python 新手,并尝试为我的学校项目编写一个 twitter 客户端。我成功地使用 2.7.5 和瓶子框架 0.10.1 创建了一个应用程序,检索用户访问令牌和访问令牌秘密,并在我的本地主机上发布了状态帖子(新推文)

但是在参数化的 get 请求中,我收到了来自 python httplib 的空响应和 400 状态代码。我将函数中的授权标头打印到控制台,并从 mac os x 进行了手动终端调用:

curl --get 'https://api.twitter.com/1.1/statuses/user_timeline.json' --data 'screen_name=bsakallioglu' --header 'Authorization: OAuth oauth_consumer_key="UVp1gtjkyF2dKteYTp7XA",oauth_nonce="U52xztXmCOGozeEXeFobTIiBhtQoqbXR",oauth_signature="mMDOmjWdBIeSGo6XeRL8yd7%2FPrM%3D%0A",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1381852017",oauth_token="331125162-r5cwlIpWkrW3aaKP40pPCFm95dBzR5OLErOrNDd3",oauth_version="1.0"' --verbose

这个有效。但是代码不起作用。可能是什么问题呢。?

代码如下:

def send_twitter_request(self, method, uri, api_params, oauth_params):
    url = self.http_protocol + self.base_uri + uri
    base_string = self.build_base_string(method, url, oauth_params, api_params)
    composite_key = self.create_composite_key(self.consumer_secret, self.oauth_token_secret)
    oauth_params['oauth_signature'] = self.create_oauth_signature(composite_key, base_string)

    headers = {'User-Agent': 'CMPE690',
               'Accept': '*/*',
               'Content-Type': 'application/x-www-form-urlencoded',
               'Authorization': self.build_authorization_header(oauth_params)}
    conn = httplib.HTTPSConnection(self.base_uri)
    conn.set_debuglevel(1)
    if api_params is not None:
        api_params = urllib.urlencode(api_params)
        print api_params

    #this one seems correct because i made curl call manually from this
    print headers['Authorization']
    conn.request(method, uri, api_params, headers)
    response = conn.getresponse()
    #here i get the 400 status and 0 response length.
    print response.status, response.length, response.reason
    data = response.read()
    conn.close()
    return data

def make_twitter_api_call(self, method, uri, post_params):
    oauth_params = {
        'oauth_consumer_key': self.consumer_key,
        'oauth_nonce': self.create_nonce(),
        'oauth_signature_method': self.oauth_signature_method,
        'oauth_timestamp': self.timestamp(),
        'oauth_token': self.oauth_token,
        'oauth_version': self.oauth_version
    }
    return self.send_twitter_request(method, '/' + self.api_version + uri + '.json',
                                     post_params, oauth_params)
#this one works
params = {}
resp = twitter_client.make_twitter_api_call('GET', '/account/settings', params)

#this doesn't
other = {'screen_name': 'bsakallioglu'}
other_resp = twitter_client.make_twitter_api_call('GET', '/statuses/user_timeline',     other)
4

0 回答 0