Twitter搜索API使用urllib2

时间:2013-12-02 19:55:46

标签: python api twitter urllib2

我是使用python(甚至只是API调用)的API调用的初学者。我正在尝试使用Twitter API进行基本调用。

我的生成oauth_signature的代码如下:

def getSignature(query):
    key_dict['q'] = urllib.quote(query, '')
    finKey = ""
    for key in sorted(key_dict.keys()):
        finKey += key + "="+key_dict[key]+"&"
    finKey =  finKey[:-1]
    finKey = HTTP_METHOD + "&" + urllib.quote(BASE_URL, '') + "&" + urllib.quote(finKey, '')
    key = urllib.quote(CONSUMER_SECRET_KEY, '')+"&"+urllib.quote(ACCESS_TOKEN_SECRET, '')
    hashed = hmac.new(key, finKey, sha1)
    finKey = binascii.b2a_base64(hashed.digest())
    key_dict['oauth_signature'] = urllib.quote(finKey, '')

其中key_dict存储所有密钥:

key_dict = dict()
key_dict['oauth_consumer_key'] = urllib.quote(CONSUMER_KEY, '')
key_dict['oauth_nonce'] = urllib.quote("9ab59691142584g739134971f75aa986", '')
key_dict['oauth_signature_method'] = urllib.quote("HMAC-SHA1", '')
key_dict['oauth_timestamp'] = urllib.quote(str(int(time.time())), '')
key_dict['oauth_token'] = urllib.quote(ACCESS_TOKEN, '')
key_dict['oauth_version'] = urllib.quote(OAUTH_VERSION, '')
BASE_URL = "https://api.twitter.com/1.1/search/tweets.json?" + urllib.quote("q=delhi+elections", '')

我使用以下代码生成基本标题字符串:

def getHeaderString():
    ret = "OAuth "
    key_list =['oauth_consumer_key', 'oauth_nonce', 'oauth_signature', 'oauth_signature_method', 'oauth_timestamp', 'oauth_token', 'oauth_version']
    for key in key_list:
        ret = ret+key+"=\""+key_dict[key]+"\", "
    ret = ret[:-2]
    return ret

虽然我正在打电话,但我得到了:

urllib2.HTTPError: HTTP Error 401: Unauthorized

OR

urllib2.URLError: <urlopen error [Errno 60] Operation timed out>

我的最终请求是使用以下内容进行的:

getSignature("delhi+elections")
headers = { 'Authorization' : getHeaderString()}
req = urllib2.Request(BASE_URL, headers= headers)
response = urllib2.urlopen(req)

我哪里错了?

2 个答案:

答案 0 :(得分:1)

应该在某处提到的几点:

  1. 方法:binascii.b2a_base64(hashed.digest())在字符串末尾添加新换行符。这会导致oauth_signature验证失败。
  2. delhi+elections实际上应该是delhi elections。这种不匹配再次使sha1中的哈希值匹配失败。
  3. 删除它们都解决了这个问题。 最终的代码:

    key_dict = dict()
    key_dict['oauth_consumer_key'] = urllib.quote(CONSUMER_KEY, '')
    key_dict['oauth_nonce'] = urllib.quote("9aa39691142584s7df134971375aa986", '')
    key_dict['oauth_signature_method'] = urllib.quote("HMAC-SHA1", '')
    key_dict['oauth_timestamp'] = urllib.quote(str(int(time.time())), '')
    key_dict['oauth_token'] = urllib.quote(ACCESS_TOKEN, '')
    key_dict['oauth_version'] = urllib.quote(OAUTH_VERSION, '')
    BASE_URL = "https://api.twitter.com/1.1/search/tweets.json"
    def getSignature(query):
        key_dict['q'] = urllib.quote(query, '')
        finKey = ""
        for key in sorted(key_dict.keys()):
            finKey += key + "="+key_dict[key]+"&"
        finKey =  finKey[:-1]
        finKey = HTTP_METHOD + "&" + urllib.quote(BASE_URL, '') + "&" + urllib.quote(finKey, '')
        key = urllib.quote(CONSUMER_SECRET_KEY, '')+"&"+urllib.quote(ACCESS_TOKEN_SECRET, '')
        hashed = hmac.new(key, finKey, sha1)
        finKey = binascii.b2a_base64(hashed.digest())[:-1]
        key_dict['oauth_signature'] = urllib.quote(finKey, '')
    
    def getHeaderString():
        ret = "OAuth "
        key_list =['oauth_consumer_key', 'oauth_nonce', 'oauth_signature', 'oauth_signature_method', 'oauth_timestamp', 'oauth_token', 'oauth_version']
        for key in key_list:
            ret = ret+key+"=\""+key_dict[key]+"\", "
        ret = ret[:-2]
        return ret
    
    url = BASE_URL
    getSignature("delhi elections")
    headers = { 'Authorization' : getHeaderString()}
    values = {'q':'delhi elections'}
    data = urllib.urlencode(values)
    req = urllib2.Request(url+"?"+data, headers= headers)
    response = urllib2.urlopen(req)
    the_page = response.read()
    print the_page
    

答案 1 :(得分:0)

您尝试使用tweepy而不是编写自己的客户端吗?对于使用此库的参考实现,您可以检查twitCheck客户端。