开发者社区> 问答> 正文

Python 3.7 TypeError:需要一个类似字节的对象,而不是'str'

我有以下两个字符串:

client_id = "id_str"
client_secret = "secret_str"

我必须像这样通过它们:

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))

但是当我这样做时,我得到了错误:

    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'

如何解决“ Python 3.7”的这种编码/格式?

ps:我看不到此答案的格式{}和编码。

问题来源:stackoverflow

展开
收起
is大龙 2020-03-23 18:56:54 404 0
1 条回答
写回答
取消 提交回答
  • 换线

    encoded = base64.b64encode("{}:{}".format(client_id, client_secret))
    

    encoded = base64.b64encode("{}:{}".format(client_id, client_secret).encode())
    

    根据文档:

    base64.b64encode(s,altchars = None)

    使用Base64对类似字节的对象进行编码,然后返回编码后的字节。

    关于您的异议:

    链接的答案不解决格式问题

    实际上,您的问题与格式化无关,因为format()仅返回一个字符串,但是b64encode需要一个类似字节的对象,而不是字符串。

    回答来源:stackoverflow

    2020-03-23 18:57:01
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载