Created
February 24, 2014 11:52
-
-
Save yukpiz/e92696be70e5befb4aaa to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import time, random, urllib, cgi, hmac, hashlib | |
print 'Twitter OAuth for python.\n' | |
print 'Consumer登録は以下より可能です。' | |
print 'http://dev.twitter.com/apps/new\n' | |
consumerKey = '$ConsumerKey' | |
consumerSecret = '$ConsumerSecret' | |
print 'Consumer key: %s' % consumerKey | |
print 'Consumer secret: %s\n' % consumerSecret | |
# Token取得Method | |
httpMethod = 'GET' | |
# Token取得用URL | |
reqTokenUrl = 'https://api.twitter.com/oauth/request_token' | |
# パラメータ辞書を生成 | |
# oauth_consumer_key: Consumer Key | |
# oauth_signature_method: 署名(HMAC-SHA1) | |
# oauth_timestamp: Unix time stamp | |
# oauth_nonce: ランダムな文字列が必要 | |
# oauth_version: 1.1 | |
requestParams = { | |
"oauth_consumer_key": consumerKey, | |
"oauth_signature_method": "HMAC-SHA1", | |
"oauth_timestamp": str(int(time.time())), | |
"oauth_nonce": str(random.getrandbits(64)), | |
"oauth_version": "1.1" | |
} | |
# パラメータ辞書をURLパラメータ用に整形 | |
# 辞書をソート | |
# URLエンコード | |
# %s=%sに整形して&で結合する | |
paramList = [] | |
for key in sorted(requestParams): | |
print '%s: %s' % (key, requestParams[key]) | |
paramList.append('%s=%s' % (urllib.quote(key, ''), urllib.quote(requestParams[key], ''))) | |
paramStr = '&'.join(paramList) | |
# リクエストメッセージを整形 | |
# HTTPメソッド、リクエストURL、パラメータを&で結合 | |
requestMessage = '%s&%s&%s' % (httpMethod, urllib.quote(reqTokenUrl, ''), urllib.quote(paramStr, '')) | |
# Consumer Secretとパラメータからダイジェストを生成 | |
# URLパラメータとしてリクエストを生成する | |
key = "%s&%s" % (consumerSecret, '') # Consumer Securetからキーを生成 | |
signature = hmac.new(key, requestMessage, hashlib.sha1) # HMACの生成 | |
digest_base64 = signature.digest().encode("base64").strip() # base64でエンコードしたダイジェスト | |
requestParams['oauth_signature'] = digest_base64 # ダイジェストをパラメータへ追加 | |
requestUrl = reqTokenUrl+ '?' + urllib.urlencode(requestParams) # URLパラメータとして結合 | |
print "\nAccess URL: %s\n" % requestUrl | |
# リクエストを送出、結果を得る | |
result = urllib.urlopen(requestUrl).read() | |
data = cgi.parse_qs(result) # Response bodyを辞書へ変換 | |
print '取得結果です\n' | |
print data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment