我正在尝试创建一个处理Twitter
个流的脚本。不幸的是,OAuth流程阻碍了我。采用我在互联网上找到的一些代码,我收到https://api.twitter.com/oauth/token的空白回复。为了更好地理解这个过程,我试图在没有特殊模块的情况下做到这一点。这是我的代码,缺少什么?任何帮助将不胜感激。
代码:
import http.client
import urllib
import base64
CONSUMER_KEY = 'yadayadayada'
CONSUMER_SECRET = 'I am really tired today'
encoded_CONSUMER_KEY = urllib.parse.quote(CONSUMER_KEY)
encoded_CONSUMER_SECRET = urllib.parse.quote(CONSUMER_SECRET)
concat_consumer_url = encoded_CONSUMER_KEY + ':' + encoded_CONSUMER_SECRET
host = 'api.twitter.com'
url = '/oauth2/token/'
params = urllib.parse.urlencode({'grant_type' : 'client_credentials'})
req = http.client.HTTPSConnection(host, timeout = 100)
req.set_debuglevel(1)
req.putrequest("POST", url)
req.putheader("Host", host)
req.putheader("User-Agent", "My Twitter 1.1")
req.putheader("Authorization", "Basic %s" % base64.b64encode(b'concat_consumer_url'))
req.putheader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
req.putheader("Content-Length", "29")
req.putheader("Accept-Encoding", "identity")
req.endheaders()
req.send(b'params')
resp = req.getresponse()
print ("{} {}".format(resp.status, resp.reason))
错误讯息:
C:\Python33>app_only_test_klug.py
Traceback <most recent call last>:
File "C:\Python33\app_only_test_klug.py", line 31, in <module>
resp = req.getresponse()
File "C:\Python33\lib\http\client.py", line 1131, in getresponse
response.being()
File "C:\Python33\lib\http\client.py", line 354, in begin
version, status, reason = self._read_status()
File "C:\Python33\lib\http\client.py", line 324, in _read_status
raise BadStatusLine(line)
http.client.BadStatusLine: ''
非常感谢任何帮助。
更新:
经过一些修补,我相信问题在于我的base64编码:
req.putheader(“授权”,“基本%s”%base64.b64encode(b'concat_consumer_url'))
当我解码上面得到的编码时,我得到“b'concat_consumer_url”,而不是在冒号周围组合的encoded_CONSUMER_KEY和encoded_CONSUMER_SECRET的串联。如何让base64对btadcode表示concat_comsumer_url所代表的值而不是字符串“concat_consumer_url”以便我可以继续前进?提前谢谢。
答案 0 :(得分:0)
我相信问题也存在 - 您应该将变量传递给编码函数,而不是将变量的名称作为字节传递,如下所示:
req.putheader("Authorization", "Basic %s" % base64.b64encode(concat_consumer_url))
再次尝试更改。