Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用urllib2的Twitter搜索API_Python_Api_Twitter_Urllib2 - Fatal编程技术网

Python 使用urllib2的Twitter搜索API

Python 使用urllib2的Twitter搜索API,python,api,twitter,urllib2,Python,Api,Twitter,Urllib2,我是使用python进行API调用的初学者(甚至只是API调用)。我正在尝试使用Twitter API进行基本调用 我的生成oauth_签名的代码如下: def getSignature(query): key_dict['q'] = urllib.quote(query, '') finKey = "" for key in sorted(key_dict.keys()): finKey += key + "="+key_dict[key]+"&

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

我的生成oauth_签名的代码如下:

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
getSignature("delhi+elections")
headers = { 'Authorization' : getHeaderString()}
req = urllib2.Request(BASE_URL, headers= headers)
response = urllib2.urlopen(req)
虽然当我打电话时,我得到:

urllib2.HTTPError: HTTP Error 401: Unauthorized


我哪里出错了?

您是否尝试过使用?对于使用此库的参考实现,您可以查看客户端。

应该在某些地方提到的几点:

  • 方法:
    binascii.b2a\u base64(hashed.digest())
    在字符串末尾追加一个新行提要。这会导致oauth_签名的身份验证失败
  • 德里+选举
    实际上应该是
    德里选举
    。这种不匹配再次导致sha1中的哈希值匹配失败
  • 把这两个都去掉就解决了问题。 最终代码:

    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
    

    是的,我看过外部图书馆。甚至
    curl
    命令也可以使用相同的头。但我正在努力避免外部依赖。
    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