【问题标题】:Failed to encode base64 in Python [duplicate]无法在 Python 中编码 base64 [重复]
【发布时间】:2020-04-03 11:38:54
【问题描述】:

我打算通过 Spotify 进行身份验证。授权用户后,这应该通过一个官方文档来获取用户信息。

来自令牌端点的 cURL 请求和响应示例如下所示:

curl -H "Authorization: Basic ZjM...zE=" -d grant_type=authorization_code -d code=MQCbtKe...44KN -d redirect_uri=https%3A%2F%2Fwww.foo.com%2Fauth https://accounts.spotify.com/api/token

通过Authorization Guide

但是它发生了这个错误:

TypeError: a bytes-like object is required, not 'str'

这是我的代码:

client_id = 'XXXXXXXXXXXXXXXXXX'
client_secret = 'XXXXXXXXXXXXXXXXXX'
oauth_scope = 'user-read-currently-playing'
redirect_uri = 'http://localhost:3000/spotify_profile/callback'

@bp.route('/redirect', methods=['GET'])
def authorize():
    authorize_url = f"https://accounts.spotify.com/authorize?response_type=code&client_id={ client_id }&scope={ oauth_scope }&redirect_uri={ redirect_uri }"

    return redirect(authorize_url)

@bp.route('/callback', methods=["GET", "POST"])
def callback():
    auth_code = request.args['code']
    auth_client = client_id + client_secret
    auth_encode = 'Basic ' + base64.b64encode(auth_client)
    ## error happens

    headers = {
        'Authorization': auth_encode,
    }
    data = {
    'grant_type': 'authorization_code',
    'code': auth_code,
    'redirect_uri': redirect_uri
    }
    response = requests.post('https://accounts.spotify.com/api/token', headers=headers, data=data)

【问题讨论】:

    标签: python spotify encode


    【解决方案1】:

    auth_client编码为字节,然后解码结果:

    auth_encode = 'Basic ' + base64.b64encode(auth_client.encode()).decode()
    

    【讨论】:

      猜你喜欢
      • 2020-03-21
      • 1970-01-01
      • 2018-03-08
      • 1970-01-01
      • 2019-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多