2014-02-08 200 views
3

於是,經過年掙扎着從https://api.twitter.com/oauth/request_token工作得到request_token的天,我終於成功生成基地簽名字符串和HMAC-SHA1簽名,並且從收到oauth_tokenhttps://api.twitter.com/oauth/request_tokenOAuth訪問令牌請求(Twitter的API)和oauth_verifier場

現在,我對下一步有些困惑。我的最終目標是能夠以編程方式簡單地推送推文。

我知道我需要從https://api.twitter.com/oauth/access_token獲得一個訪問令牌,但我不完全確定如何繼續。我知道我需要將收到的oauth_token值發送到/oauth/access_token,但我在Authorization標頭中的oauth_verifier字段在概念上使我感到困惑。

關於這次談話中重定向用戶的瀏覽器的登錄頁,然後將其用於生產引腳數爲oauth_verifier方面大多數教程或文檔。但在我的情況下,沒有瀏覽器:我只是在Python中編寫一個自動守護程序,需要定期發送特定的推文。所以沒有瀏覽器,也沒有涉及人類「用戶」。那麼oauth_verifier字段在這裏適用?

+0

難道我的答案w^ork給你? –

回答

7

你在找什麼是application-only authentication

下面是一個例子的Python 3.3,如何獲得你可以使用應用程序只要求使用requests包並假設值consumer_keyconsumer_secret分別持有你的Twitter API用戶密鑰和密碼承載令牌:

import base64 
import requests 

# get bearer token for application only requests 
bearer_token_credentials = base64.urlsafe_b64encode(
    '{}:{}'.format(consumer_key, consumer_secret).encode('ascii')).decode('ascii') 
url = 'https://api.twitter.com/oauth2/token' 
headers = { 
    'Authorization': 'Basic {}'.format(bearer_token_credentials), 
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', 
} 
data = 'grant_type=client_credentials' 
response = requests.post(url, headers=headers, data=data) 
response_data = response.json() 
if response_data['token_type'] == 'bearer': 
    bearer_token = response_data['access_token'] 
else: 
    raise RuntimeError('unexpected token type: {}'.format(response_data['token_type'])) 

承載令牌可以用來創建授權標題爲您的要求是這樣的:

headers = { 
    'Authorization': 'Bearer {}'.format(bearer_token), 
    'Accept-Encoding': 'gzip', 
}