gpt4 book ai didi

python - urllib.request.Request 说参数无效

转载 作者:行者123 更新时间:2023-12-01 04:54:01 29 4
gpt4 key购买 nike

我收到以下错误:TypeError:序列项 0:预期字节、字节数组或具有缓冲区接口(interface)的对象、找到元组

我检查了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

最佳答案

authorization = "Basic %s", bearerTokenCredentials

这一行是错误。 authorization 变成一个元组而不是一个字符串。轻松修复:

authorization = "Basic %s" % bearerTokenCredentials

关于python - urllib.request.Request 说参数无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27833629/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com