Twitter OAuth无法验证我的Python命令行工具

时间:2014-07-04 09:03:51

标签: python twitter oauth

我花了好几个小时沮丧,现在我有了这个:

import requests, json, urllib
import time
import string, random

from hashlib import sha1
import hmac, binascii

def twitterIDGenerator(length):
    toRet = ""
    for i in range(0, length):
        toRet = toRet + random.choice(string.hexdigits)
    return toRet

def twitterSignatureGenerator(baseString, keyString):
    hashed = hmac.new(keyString, baseString, sha1)
    return binascii.b2a_base64(hashed.digest()).rstrip('\n')

OAUTH_CONSUMER_KEY = ''
OAUTH_NONCE = twitterIDGenerator(32)
OAUTH_SIGNATURE_METHOD = 'HMAC-SHA1'
OAUTH_TIMESTAMP = str(int(time.time()))
OAUTH_VERSION = '1.0'

# Get request token from Twitter
request_tokenURL = 'https://api.twitter.com/oauth/request_token'

request_tokenParameterString = ("oauth_consumer_key=" + OAUTH_CONSUMER_KEY + 
        "&oauth_nonce=" + OAUTH_NONCE + "&oauth_signature_method=" + 
        OAUTH_SIGNATURE_METHOD + "&oauth_timestamp=" + OAUTH_TIMESTAMP + 
        "&oauth_version=" + OAUTH_VERSION)
request_tokenSigBaseString = ("POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&" +
        urllib.quote(request_tokenParameterString))

request_tokenSignature = twitterSignatureGenerator(request_tokenSigBaseString, 
        '[REDACTED consumer secret key]')
request_tokenHeaders = {'oauth_nonce': OAUTH_NONCE,
                        'oauth_callback': 'oob',
                        'oauth_signature_method': OAUTH_SIGNATURE_METHOD,
                        'oauth_timestamp': OAUTH_TIMESTAMP,
                        'oauth_consumer_key': OAUTH_CONSUMER_KEY,
                        'oauth_signature': urllib.quote(request_tokenSignature),
                        'oauth_version': OAUTH_VERSION}

request_tokenResponse = requests.post(request_tokenURL, headers=request_tokenHeaders)
print request_tokenResponse.text

到目前为止,它应该返回一个request_token,这样我就可以让我的用户访问PIN网站,这样我就可以获得access_token了。但我得到了#34;无法验证oauth签名和令牌"来自Twitter。

可能的原因是错误的URL编码。我看到Twitter需要RFC3986编码。有没有办法在Python中执行此操作?如果是的话,我应该只在我目前使用urllib.quote的两个位置进行吗?我的oauth_signature是否正确生成了?

The documentation令人烦恼。

0 个答案:

没有答案