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

调用Spotipy的current_user_recently_played遇属性错误,求解决

解决Spotipy中current_user_recently_played属性不存在的问题

我来帮你搞定这个报错,这个问题其实很常见,主要有两个核心原因,对应两种清晰的解决方案:

为什么会出现这个错误?

你看到的AttributeError: 'Spotify' object has no attribute 'current_user_recently_played',无非两种情况:

  1. 你的Spotipy版本太老了:current_user_recently_played是Spotipy官方后来新增的方法,旧版本的库根本没有这个内置方法。
  2. 你自定义的方法没和实例绑定:你自己写了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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:02:49