utf-8解码问题-python

问题描述 投票:0回答:2

我正在关注视频(https://www.youtube.com/watch?v=WAmEZBEeNmg&t=847s)以便通过 python 与 Spotify 进行交互

from dotenv import load_dotenv
import os
import base64
from requests import post
import json

load_dotenv()

client_id = os.getenv("CLIENT_ID")
client_secret = os.getenv("CLIENT_SECRET")


def get_token():
    auth_string = client_id + ":" + client_secret
    auth_bytes = auth_string.encode("utf-8")
    auth_base64 = str(base64.b64decode(auth_bytes), "utf-8")

    url = "https://accounts.spotify.com/api/token"
    headers = {
        "Authorization": "Basic " + auth_base64,
        "Content-type": "application/x-www-form-urlencoded"
    }
    data = {"grant_type": "client_credentials"}
    result = post(url, headers=headers, data=data)
    json_result = json.loads(result.content)
    token = json_result["access_token"]
    return token

token = get_token()
print(token)

我收到了这个错误

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 0: invalid continuation byte

python base64 spotify
2个回答
1
投票

使用请求库,获取您使用的查询的 JSON 响应:

result.json()

如果响应包含 JSON 响应,这将返回一个字典对象。
您不需要使用 JSON 库将其转换为字典。它会为你做到这一点。

但是,在您的代码示例中您使用了:

result.content

这不会返回字典,而是返回类似字节的对象。
当您使用

json.loads
result.content
作为字典加载时,您遇到的错误很可能会发生,但是它(可能不)根本不包含类似 JSON 的数据,因此它会显示错误。

不过我可能是错的,这个错误出现在其他地方。您的问题没有提供出现错误的足够上下文。


0
投票

此代码可以工作

演示代码

from dotenv import load_dotenv
import os
import base64
from requests import post
import json

load_dotenv()

client_id = os.getenv("CLIENT_ID")
client_secret = os.getenv("CLIENT_SECRET")

def get_token():
    b64_bytes = (client_id + ":" + client_secret).encode('ascii')
    auth_base64 = str(base64.b64encode(b64_bytes), 'UTF-8')
    
    url = "https://accounts.spotify.com/api/token"
    headers = {
        "Authorization": "Basic " + auth_base64,
        "Content-type": "application/x-www-form-urlencoded"
    }
    data = {
        "grant_type": "client_credentials",
        'scope' : 'playlist-modify-private,playlist-modify-public'
    }
    result = post(url, headers=headers, data=data)
    json_result = json.loads(result.content)
    token = json_result["access_token"]
    return token

token = get_token()
print(token)

结果

设置环境变量

在 Windows 中

SET CLIENT_ID=<your client id>
SET CLIENT_SECRET=<your client secret>

在 Linux/Mac 中

EXPORT CLIENT_ID=<your client id>
EXPORT CLIENT_SECRET=<your client secret>

这个版本也可以

    auth_string = f'{client_id}:{client_secret}'
    auth_bytes = auth_string.encode('utf-8')
    auth_base64 = str(base64.b64encode(auth_bytes), 'utf-8')
© www.soinside.com 2019 - 2024. All rights reserved.