调用Spotipy的current_user_recently_played遇属性错误,求解决
解决Spotipy中
current_user_recently_played属性不存在的问题 我来帮你搞定这个报错,这个问题其实很常见,主要有两个核心原因,对应两种清晰的解决方案:
为什么会出现这个错误?
你看到的AttributeError: 'Spotify' object has no attribute 'current_user_recently_played',无非两种情况:
- 你的Spotipy版本太老了:
current_user_recently_played是Spotipy官方后来新增的方法,旧版本的库根本没有这个内置方法。 - 你自定义的方法没和实例绑定:你自己写了
current_user_recently_played函数,但只是孤零零定义着,没有关联到你创建的spotify实例上,所以实例调用时找不到它。
解决方案
首选方案:升级Spotipy到最新版
这是最省心的办法,官方已经把这个方法封装好了,不用自己手写。打开终端跑这个命令升级:
pip install --upgrade spotipy
升级完成后,删掉你自己写的current_user_recently_played函数,直接用官方方法就行,你的代码可以优化成这样(顺便把文件操作改成更安全的with语句):
import spotipy import spotipy.util as util import json token = util.prompt_for_user_token( username="212887@studenti.unimore.it", scope="user-read-recently-played user-read-private user-top-read user-read-currently-playing", client_id="xxxxxxxxxxxxxxxxxxxxxx", client_secret="xxxxxxxxxxxxxxxxxxxxxx", redirect_uri="https://www.google.it/" ) spotify = spotipy.Spotify(auth=token) # 直接调用官方方法 canzonirecenti = spotify.current_user_recently_played(limit=50) # 用with语句自动管理文件,避免遗漏关闭 with open("canzonirecenti.json", "w") as out_file: json.dump(canzonirecenti, out_file, sort_keys=True, indent=2) print(json.dumps(canzonirecenti, sort_keys=True, indent=2))
备选方案:无法升级时,手动绑定自定义方法
如果因为环境限制不能升级库,那可以把你写的方法绑定到spotify实例上,修改代码如下:
import spotipy import spotipy.util as util import json def current_user_recently_played(self, limit=50): return self._get('me/player/recently-played', limit=limit) token = util.prompt_for_user_token( username="212887@studenti.unimore.it", scope="user-read-recently-played user-read-private user-top-read user-read-currently-playing", client_id="xxxxxxxxxxxxxxxxxxxxxx", client_secret="xxxxxxxxxxxxxxxxxxxxxx", redirect_uri="https://www.google.it/" ) spotify = spotipy.Spotify(auth=token) # 把自定义方法绑定到实例上,让实例能调用它 spotify.current_user_recently_played = current_user_recently_played.__get__(spotify, spotipy.Spotify) canzonirecenti = spotify.current_user_recently_played(limit=50) with open("canzonirecenti.json", "w") as out_file: json.dump(canzonirecenti, out_file, sort_keys=True, indent=2) print(json.dumps(canzonirecenti, sort_keys=True, indent=2))
额外提醒
- 你的
scope参数已经包含了user-read-recently-played,这是调用该接口的必要权限,这部分没问题~ - 确保
util.prompt_for_user_token能成功获取到有效的授权令牌,如果token获取失败也会间接导致后续调用出问题。
内容的提问来源于stack exchange,提问作者Jessica Martini
相关产品推荐
相关产品推荐

