我試圖使用Python 3與Twitter的API接口返回鏈接頁面,讓我一個PIN碼,用來請求訪問令牌。詳細在這裏:https://dev.twitter.com/docs/auth/pin-based-authorization從Twitter的API獲取請求令牌與Python 3
Twitter的API響應我告訴我,我沒有通過返回401正確授權我的POST請求。我最好的猜測是爲什麼我沒有正確編碼base64中的HMAC簽名。根據我看過的正確的POST請求示例,我生成的POST請求的其他部分顯示正確。
我花了好幾天這方面的工作,我希望有人能幫助我輕移過去的最後一部分。
以下是Twitter的API文檔的最相關的部分:https://dev.twitter.com/docs/api/1/post/oauth/request_token
https://dev.twitter.com/docs/auth/authorizing-request
這是我使用的代碼:
import urllib.parse, urllib.request, json
from hashlib import sha1
import hmac
import binascii
import time
import random
import sys
#Server Links
REQUEST_URL = "https://api.twitter.com/oauth/request_token";
ACCESS_URL = "https://api.twitter.com/oauth/access_token";
AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize";
#Consumer keys
TOKEN = "Omitted"
TOKEN_SECRET = "Omitted"
#Access keys
ACCESS_TOKEN = ""
ACCESS_TOKEN_SECRET = ""
TWEET = ""
count = 1
while len(sys.argv) > count:
TWEET += sys.argv[count] + " "
count += 1
TWEET = TWEET[:-1] #Get rid of trailing space
print(TWEET + "\n")
#Build content header for POST to return request tokens
HEADER_TITLE = "Authorization:"
#Consumer key
HEADER = 'OAuth oauth_callback="oob" oauth_consumer_key="' + TOKEN + '", '
#Nonce
HEADER += 'oauth_nonce="'
NONCE = ""
for i in range(32):
NONCE += chr(random.randint(97, 122))
HEADER += NONCE
HEADER += '", '
#Timestamp
TIMESTAMP = str(int(time.time()))
#Signature
HEADER += 'oauth_signature="'
PARAMETER_STRING = "include_entities=true&oauth_consumer_key=" + TOKEN + "&oauth_nonce=" + NONCE + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp=" + TIMESTAMP + "&oauth_version=1.0"
BASE_STRING = 'POST&' + urllib.parse.quote(REQUEST_URL, '') + '&' + urllib.parse.quote(PARAMETER_STRING, '')
SIGNING_KEY = urllib.parse.quote(TOKEN_SECRET, '') + '&'
print("DEBUG : SIGNING KEY " + SIGNING_KEY + " BASE STRING " + BASE_STRING + "\n")
HEADER += str(binascii.b2a_base64(hmac.new(BASE_STRING.encode(), SIGNING_KEY.encode(), sha1).digest()[:-1]))#Note to self, we may not want to remove the last character...
HEADER += '", '
#Signature Method
HEADER += 'oauth_signature_method="HMAC-SHA1", '
#Timestamp
HEADER += 'oauth_timestamp="' + TIMESTAMP + '", '
#Version
HEADER += 'oauth_version="1.0"'
print(HEADER_TITLE + "\n" + HEADER)
print(urllib.request.urlopen(urllib.request.Request(REQUEST_URL, bytes(HEADER_TITLE+HEADER, 'utf-8'))).read())
最後,我想指出,我我意識到Python OAuth和Twitter模塊的存在,它們有助於開發此模塊。但是,作爲一種學習體驗,我選擇不使用它們。
預先感謝您對我付出的時間和幫助。
是否已確認這包Python3K的作品? – 2012-04-10 00:21:45