我收到以下错误:TypeError: sequence item 0: expected bytes, bytearray, or an object with the buffer interface, tuple found
我检查了Python文档,urllib.request.Request的参数似乎是正确的类型。 urllib中的POST请求需要哪些类型?
import urllib.parse
import urllib.request
import base64
class TweetGrabber:
def __init__(self, key, secret):
myKey = urllib.parse.quote_plus(key)
mySecret = urllib.parse.quote_plus(secret)
bearerTokenCredentials = myKey + ":" + mySecret
bearerTokenCredentials = bytes(bearerTokenCredentials, "utf-8")
bearerTokenCredentials = base64.b64encode(bearerTokenCredentials)
url = 'https://api.twitter.com/oauth2/token'
userAgent = "Tau v0.1"
authorization = "Basic %s", bearerTokenCredentials
contentLength = 29
acceptEncoding = "gzip"
contentType = "application/x-www-form-urlencoded;charset=UTF-8"
values = {'grant_type' : 'client_credentials'}
headers = {'User-Agent' : userAgent, 'Authorization' : authorization, 'Content-Type' : contentType, 'Content-Length' : contentLength, 'Accept-Encoding' : acceptEncoding}
data = urllib.parse.urlencode(values)
data = data.encode('utf-8')
req = urllib.request.Request(url, data, headers)
response = urllib.request.urlopen(req)
print(response.read())
编辑:整个错误消息
Traceback (most recent call last):
File "TweetGrabber.py", line 27, in <module>
x = TweetGrabber("key", "secret")
File "TweetGrabber.py", line 24, in __init__
response = urllib.request.urlopen(req)
File "C:\python34\lib\urllib\request.py", line 153, in urlopen
return opener.open(url, data, timeout)
File "C:\python34\lib\urllib\request.py", line 455, in open
response = self._open(req, data)
File "C:\python34\lib\urllib\request.py", line 473, in _open
'_open', req)
File "C:\python34\lib\urllib\request.py", line 433, in _call_chain
result = func(*args)
File "C:\python34\lib\urllib\request.py", line 1217, in https_open
context=self._context, check_hostname=self._check_hostname)
File "C:\python34\lib\urllib\request.py", line 1174, in do_open
h.request(req.get_method(), req.selector, req.data, headers)
File "C:\python34\lib\http\client.py", line 1090, in request
self._send_request(method, url, body, headers)
File "C:\python34\lib\http\client.py", line 1123, in _send_request
self.putheader(hdr, value)
File "C:\python34\lib\http\client.py", line 1069, in putheader
value = b'\r\n\t'.join(values)
TypeError: sequence item 0: expected bytes, bytearray, or an object with the buf
fer interface, tuple found
答案 0 :(得分:2)
authorization = "Basic %s", bearerTokenCredentials
此行是错误。 authorization
成为元组而不是字符串。轻松修复:
authorization = "Basic %s" % bearerTokenCredentials