You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Spotify API授权流程时遇TypeError: 'module' object is not callable错误

解决Spotify API授权流程中的TypeError: 'module' object is not callable错误

错误根源

你遇到的错误是因为直接将base64模块当作函数调用了(base64(auth_bytes))。base64是Python标准库的模块,本身不可调用,必须使用模块内的方法(比如b64encode)来完成编码操作。

虽然你尝试改用base64.b64encode(auth_bytes).decode('utf-8'),但问题仍存在的原因很可能是**get_info函数不完整**——当前代码片段只做了base64编码,没有向Spotify的token端点发送请求来获取令牌,导致函数无法返回access_token、refresh_token和expires_in三个值,后续赋值逻辑也会出错。

完整修复方案

1. 修正编码与授权流程

确保使用base64.b64encode()方法完成编码,同时完善get_info函数的完整授权逻辑:

import os
import base64
import requests
from flask import request, Flask
from flask_cors import cross_origin

app = Flask(__name__)

def get_info(code):
    client_id = os.getenv("Spotify_Client_ID")
    client_secret = os.getenv("Spotify_Client_Secret")
    
    # 正确的Base64编码方式
    auth_string = f"{client_id}:{client_secret}"
    auth_bytes = auth_string.encode('utf-8')
    auth_base64 = base64.b64encode(auth_bytes).decode('utf-8')
    
    # 向Spotify令牌端点发送POST请求
    token_url = "https://accounts.spotify.com/api/token"
    headers = {
        "Authorization": f"Basic {auth_base64}",
        "Content-Type": "application/x-www-form-urlencoded"
    }
    data = {
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": "YOUR_REDIRECT_URI"  # 替换为你在Spotify开发者后台配置的重定向URI
    }
    
    response = requests.post(token_url, headers=headers, data=data)
    if response.status_code == 200:
        token_data = response.json()
        return token_data.get("access_token"), token_data.get("refresh_token"), token_data.get("expires_in")
    else:
        # 打印错误信息用于排查
        print(f"授权失败:{response.json()}")
        return None, None, None

@app.route('/callback')
@cross_origin()
def getToken(): 
    print("INSIDE CALLBACK *****")
    code = request.args.get('code')

    if code:
        access_token, refresh_token, expires_in = get_info(code)
        if access_token:
            return f"Authentication successful! Access Token: {access_token}"
        else:
            return "Failed to obtain access token."
    else: 
        return "Authorization code not found in callback request."

if __name__ == "__main__":
    app.run(debug=True)

2. 关键注意事项

  • 重定向URI匹配:data中的redirect_uri必须与你在Spotify开发者控制台中设置的完全一致(包括协议、域名、端口和路径),否则会返回授权错误。
  • 环境变量验证:确保Spotify_Client_ID和Spotify_Client_Secret这两个环境变量已正确设置,且能被Python代码读取到。
  • 依赖安装:确认已安装requests库,可通过pip install requests完成安装。

内容的提问来源于stack exchange,提问作者remycodes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 21:53:20