[英]Python 3.7 TypeError: a bytes-like object is required, not 'str'
I have these two strings:我有这两个字符串:
client_id = "id_str"
client_secret = "secret_str"
And I must pass them like so:我必须像这样传递它们:
def getToken(code, client_id, client_secret, redirect_uri):
body = {
"grant_type": 'authorization_code',
"code" : code,
"redirect_uri": redirect_uri,
"client_id": client_id,
"client_secret": client_secret
}
encoded = base64.b64encode("{}:{}".format(client_id, client_secret))
headers = {"Content-Type" : HEADER, "Authorization" : "Basic {}".format(encoded)}
post = requests.post(SPOTIFY_URL_TOKEN, params=body, headers=headers)
return handleToken(json.loads(post.text))
but when I do so I get the error:但是当我这样做时,我收到错误:
encoded = base64.b64encode("{}:{}".format(client_id, client_secret))
File "/usr/local/lib/python3.7/base64.py", line 58, in b64encode
encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'
How do I fix this encoding/formatting for Python 3.7
?如何修复Python 3.7
这种编码/格式?
ps: I don't see this answer adressing formatting {} as well as encoding. ps:我没有看到这个答案涉及格式 {} 和编码。
Change the line换线
encoded = base64.b64encode("{}:{}".format(client_id, client_secret))
to到
encoded = base64.b64encode("{}:{}".format(client_id, client_secret).encode())
According to the documentation :根据文档:
base64.b64encode(s, altchars=None) base64.b64encode(s, altchars=None)
Encode the bytes-like object s using Base64 and return the encoded bytes.使用 Base64 对类字节对象 s 进行编码并返回编码后的字节。
Regarding your objection:关于您的反对意见:
the linked answer does not address formatting链接的答案没有解决格式问题
Actually your problem has nothing to do with formatting, because format()
just returns a string, but b64encode
requires a bytes-like object, not a string.实际上你的问题与格式化无关,因为format()
只返回一个字符串,但b64encode
需要一个类似字节的对象,而不是一个字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.