簡體   English   中英

Python 3.7 TypeError:需要類似字節的對象,而不是“str”

[英]Python 3.7 TypeError: a bytes-like object is required, not '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:我沒有看到這個答案涉及格式 {} 和編碼。

換線

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

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

根據文檔

base64.b64encode(s, altchars=None)

使用 Base64 對類字節對象 s 進行編碼並返回編碼后的字節。

關於您的反對意見:

鏈接的答案沒有解決格式問題

實際上你的問題與格式化無關,因為format()只返回一個字符串,但b64encode需要一個類似字節的對象,而不是一個字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM