Как получить объект истории прослушивания с помощью spotipy? - PullRequest
0 голосов
/ 10 мая 2018

Я работаю в системе рекомендаций для Spotify и использую spotipy на Python. Я не могу использовать функцию current_user_recently_played, потому что Python говорит, что атрибут current_user_recently_played недействителен.

Я не знаю, как решить эту проблему, мне абсолютно необходима эта информация для продолжения моей работы.

Это мой код:

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)



canzonirecenti= spotify.current_user_recently_played(limit=50) 
out_file = open("canzonirecenti.json","w") 
out_file.write(json.dumps(canzonirecenti, sort_keys=True, indent=2)) 
out_file.close()

print json.dumps(canzonirecenti, sort_keys=True, indent=2)

и ответ:

AttributeError: 'Spotify' object has no attribute 'current_user_recently_played'

1 Ответ

0 голосов
/ 14 мая 2018

Конечные точки API Spotify current_user_recently_added существуют в исходном коде на Github, но, похоже, его нет в моей локальной установке.Я думаю, что версия в индексе пакета Python устарела, последнее изменение в исходном коде было 8 месяцев назад, а последнее изменение в версии PyPI - более года назад.

Я получил пример кодаработать, исправляя клиентский объект Spotify, чтобы добавить метод самостоятельно, но этот способ обычно не самый лучший, поскольку он добавляет настраиваемое поведение к конкретному экземпляру, а не к общему классу.

import spotipy
import spotipy.util as util
import json

import types


def current_user_recently_played(self, limit=50):
    return self._get('me/player/recently-played', limit=limit)


token = util.prompt_for_user_token(
        username="xxxxxxxxxxxxxx",
        scope="user-read-recently-played user-read-private user-top-read user-read-currently-playing",
        client_id="xxxxxxxxxxxxxxxxxxxxxx",
        client_secret="xxxxxxxxxxxxxxxxxxxxxxxx",
        redirect_uri="https://www.google.it/")

spotify = spotipy.Spotify(auth=token)
spotify.current_user_recently_played = types.MethodType(current_user_recently_played, spotify)

canzonirecenti = spotify.current_user_recently_played(limit=50)
out_file = open("canzonirecenti.json","w")
out_file.write(json.dumps(canzonirecenti, sort_keys=True, indent=2))
out_file.close()

print(json.dumps(canzonirecenti, sort_keys=True, indent=2))

Другие способы заставить его работать более корректно:

  • установка его из источника на Github вместо того, чтобы через Pip
  • тыкать Plamere, чтобы запросить обновление версии наPyPI
  • создает подкласс клиентского класса Spotify и добавляет недостающие методы в подкласс (возможно, самый быстрый и простой)

Вот частичный фрагмент способа, которым я подклассировал его в моемсобственный проект:

class SpotifyConnection(spotipy.Spotify):
    """Modified version of the spotify.Spotipy class

  Main changes are:
    -implementing additional API endpoints (currently_playing, recently_played)
    -updating the main internal call method to update the session and retry once on error,
     due to an issue experienced when performing actions which require an extended time
     connected.
  """

    def __init__(self, client_credentials_manager, auth=None, requests_session=True, proxies=None,
                 requests_timeout=None):
        super().__init__(auth, requests_session, client_credentials_manager, proxies, requests_timeout)

    def currently_playing(self):
        """Gets whatever the authenticated user is currently listening to"""
        return self._get("me/player/currently-playing")

    def recently_played(self, limit=50):
        """Gets the last 50 songs the user has played

    This doesn't include whatever the user is currently listening to, and no more than the
    last 50 songs are available.
    """
        return self._get("me/player/recently-played", limit=limit)

        <...more stuff>
...