OAuth访问令牌请求(Twitter API)和oauth_verifier字段

3

所以,在努力几天后,我终于成功生成了一个Base Signature String和HMAC-SHA1签名,并从 https://api.twitter.com/oauth/request_token 接收到了一个 oauth_token

现在,我对接下来的步骤有点困惑。我的最终目标是能够通过程序自动抓取推文。

我知道我需要从 https://api.twitter.com/oauth/access_token 获取一个访问令牌,但我不确定如何继续。我知道我需要将调用 /oauth/request_token 后接收到的 oauth_token 值发送到 /oauth/access_token,但我对 Authorization 头中的 oauth_verifier 字段感到概念上的困惑。

关于这一点,大多数教程或文档都涉及到“重定向用户的浏览器到登录页面”,然后使用此页面产生一个oauth_verifierpin码。 但在我的情况下,没有浏览器:我只是在Python中编写一个自动化守护进程,需要定期获取某些推文。 因此,这里没有浏览器,也没有人类“用户”。那么在这种情况下,oauth_verifier 字段如何应用呢?


我的答案对你有用吗? - Pedro Romano
1个回答

8
你需要的是仅应用程序身份验证
以下是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',
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接