我正在寻找一个工作流程来尝试和自动化应用程序的Twitter认证与特定用户。为了实现这一点(在我看来:我是OAuth工作流的一个开始),我必须创建一个通过web登录到Twitter的会话。在
使用以下代码,仅应用程序工作流相对容易建立:
consumer_key = API_key = "app API key"
consumer_secret = API_secret = "app API secret"
encoded_secrets = base64.b64encode(consumer_key+":"+consumer_secret) # key & secret should be URL-encoded
r = requests.post("https://api.twitter.com/oauth2/token",
headers={"authorization": "Basic "+encoded_secrets },
data={"grant_type": "client_credentials"})
这将检索可用于向Twitter验证应用程序的承载令牌,而无需任何用户交互。例如
^{pr2}$此代码工作正常(当头被省略时,由于身份验证失败而失败)。在
然而,当涉及到使用用户身份对应用程序进行授权时,由于必须对帐户身份进行身份验证,事情就更复杂了。标准的工作流程是在用户的web浏览器中打开一个链接,允许他们授权应用程序通过web访问他们的详细信息(通过单击按钮并提交表单)。在
当试图使用来自程序的请求而不是web浏览器来自动登录时,问题就出现了。我现在的尝试是这样的。在
# access the Twitter login page to receive a '_twitter_sess' session cookie.
twit_response = requests.get("https://twitter.com/login")
# Submit sign-on form through the web
TW_ID = "username"
TW_PW = "password"
login_data = {
"session[username_or_email]": TW_ID,
"session[password]": TW_PW,
"return_to_ssl": True,
"scribe_log": "",
"redirect_after_login": "http://holdenweb.com/contact",
"force_login": True
}
login_response = requests.post("https://twitter.com/sessions",
data=login_data,
cookies=twit_response.cookies,
headers={"User-Agent": "Mozilla/5.0 "
"(Macintosh; Intel Mac OS X 10.8; rv:24.0) "
"Gecko/20100101 Firefox/24.0"})
这失败了(但是因为这不是web身份验证,它会收到200个响应)。我还注意到,尽管cookies=twit_response.cookies
参数是requests.post()
,但请求似乎没有包含会话cookie,而且用户代理头仍然不正确。但是,我不确定这是否是失败的原因,所以我只提到这一点,以防万一。在
trrh = twit_response.request.headers
for header in trrh:
print "%s: %s" % (header, trrh[header])
印刷品
Accept-Encoding: gzip, deflate, compress
Accept: */*
User-Agent: python-requests/2.2.1 CPython/2.7.2 Darwin/12.5.0
有人能帮我取得进展吗?我觉得我忽略了一些基本的,可能是很简单的错误。在
目前没有回答
相关问题 更多 >
编程相关推荐