当前位置: 首页>>代码示例>>Python>>正文


Python spotipy.Spotify方法代码示例

本文整理汇总了Python中spotipy.Spotify方法的典型用法代码示例。如果您正苦于以下问题:Python spotipy.Spotify方法的具体用法?Python spotipy.Spotify怎么用?Python spotipy.Spotify使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在spotipy的用法示例。


在下文中一共展示了spotipy.Spotify方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: prompt_for_user_playlist

# 需要导入模块: import spotipy [as 别名]
# 或者: from spotipy import Spotify [as 别名]
def prompt_for_user_playlist(self, username):
        """
        An interactive method that will display user's playlists
        and prompt to make a selection.

        Parameters
        ----------
        username: `str`
            Spotfiy username.

        Returns
        -------
        spotify_uri: `str`
            Spotify URI for the selected playlist.
        """
        playlists = self.fetch_user_playlist_urls(username)
        for i, playlist in enumerate(playlists, 1):
            playlist_details = "{0}. {1:<30}  ({2} tracks)".format(
                i, playlist["name"], playlist["tracks"]["total"]
            )
            print(playlist_details, file=sys.stderr)
        print("", file=sys.stderr)
        playlist = spotdl.util.prompt_user_for_selection(playlists)
        return playlist["external_urls"]["spotify"] 
开发者ID:ritiek,项目名称:spotify-downloader,代码行数:26,代码来源:spotify.py

示例2: write_playlist_tracks

# 需要导入模块: import spotipy [as 别名]
# 或者: from spotipy import Spotify [as 别名]
def write_playlist_tracks(self, playlist, target_path=None):
        """
        Writes playlist track URIs to file.

        Parameters
        ----------
        playlist: `dict`
            Spotify API response object for the playlist endpoint.

        target_path: `str`
            Write Spotify track URIs to this file.
        """
        tracks = playlist["tracks"]
        if not target_path:
            target_path = u"{0}.txt".format(slugify(playlist["name"], ok="-_()[]{}"))
        return self.write_tracks(tracks, target_path) 
开发者ID:ritiek,项目名称:spotify-downloader,代码行数:18,代码来源:spotify.py

示例3: fetch_album

# 需要导入模块: import spotipy [as 别名]
# 或者: from spotipy import Spotify [as 别名]
def fetch_album(self, album_uri):
        """
        Fetches album.

        Parameters
        ----------
        album_uri: `str`
            Spotify album URI.

        Returns
        -------
        album: `dict`
            Spotify API response object for the album endpoint.
        """
        logger.debug('Fetching album "{album}".'.format(album=album_uri))
        try:
            album = self.spotify.album(album_uri)
        except spotipy.client.SpotifyException:
            msg = ('Unable to find album "{}". Make sure the album ID is correct '
                   'and then try again.'.format(album_uri))
            logger.error(msg)
            raise spotdl.helpers.exceptions.SpotifyAlbumNotFoundError(msg)
        else:
            return album 
开发者ID:ritiek,项目名称:spotify-downloader,代码行数:26,代码来源:spotify.py

示例4: write_album_tracks

# 需要导入模块: import spotipy [as 别名]
# 或者: from spotipy import Spotify [as 别名]
def write_album_tracks(self, album, target_path=None):
        """
        Writes album track URIs to file.

        Parameters
        ----------
        album: `dict`
            Spotify API response object for the album endpoint.

        target_path: `str`
            Write Spotify track URIs to this file.
        """
        tracks = self.spotify.album_tracks(album["id"])
        if not target_path:
            target_path = u"{0}.txt".format(slugify(album["name"], ok="-_()[]{}"))
        return self.write_tracks(tracks, target_path) 
开发者ID:ritiek,项目名称:spotify-downloader,代码行数:18,代码来源:spotify.py

示例5: write_all_albums

# 需要导入模块: import spotipy [as 别名]
# 或者: from spotipy import Spotify [as 别名]
def write_all_albums(self, albums, target_path=None):
        """
        Writes tracks from all albums into a file.

        Parameters
        ----------
        albums: `str`
            Spotfiy API response received in :func:`fetch_albums_from_artist`.

        target_path: `str`
            Write Spotify track URIs to this file.
        """
        # if no file if given, the default save file is in the current working
        # directory with the name of the artist
        if target_path is None:
            target_path = albums[0]["artists"][0]["name"] + ".txt"

        for album in albums:
            logger.info('Fetching album "{album}".'.format(album=album["name"]))
            self.write_album_tracks(album, target_path=target_path) 
开发者ID:ritiek,项目名称:spotify-downloader,代码行数:22,代码来源:spotify.py

示例6: ask_for_credentials

# 需要导入模块: import spotipy [as 别名]
# 或者: from spotipy import Spotify [as 别名]
def ask_for_credentials(**credentials_found):
    print(
        """You need to register as a developer and create a Spotify app in order to use spotify-onthego.
You may create an app here: https://developer.spotify.com/my-applications/#!/applications/create
You also need to register a youtube app developer key. The app key can be
obtained for free here: https://console.cloud.google.com/apis/api/youtube/overview
Please enter your app credentials:"""
    )
    username = credentials_found.get("USERNAME") or input("Spotify username: ")
    client_id = credentials_found.get("CLIENT_ID") or input("Spotify client ID: ")
    client_secret = credentials_found.get("CLIENT_SECRET") or input(
        "Spotify client secret: "
    )
    redirect_uri = credentials_found.get("REDIRECT_URI") or input(
        "Spotify redirect URI: "
    )
    google_developer_key = credentials_found.get("GOOGLE_DEVELOPER_KEY") or input(
        "Google developer key: "
    )
    return username, client_id, client_secret, redirect_uri, google_developer_key 
开发者ID:regisb,项目名称:spotify-onthego,代码行数:22,代码来源:auth.py

示例7: save_credentials

# 需要导入模块: import spotipy [as 别名]
# 或者: from spotipy import Spotify [as 别名]
def save_credentials(
    username, client_id, client_secret, redirect_uri, google_developer_key
):
    credentials_path = get_credentials_path()
    print("Saving Spotify and Youtube credentials to", credentials_path)
    check_directory_exists(credentials_path)
    with open(credentials_path, "w") as credentials_file:
        json.dump(
            {
                "USERNAME": username,
                "CLIENT_ID": client_id,
                "CLIENT_SECRET": client_secret,
                "REDIRECT_URI": redirect_uri,
                "GOOGLE_DEVELOPER_KEY": google_developer_key,
            },
            credentials_file,
        ) 
开发者ID:regisb,项目名称:spotify-onthego,代码行数:19,代码来源:auth.py

示例8: get_token

# 需要导入模块: import spotipy [as 别名]
# 或者: from spotipy import Spotify [as 别名]
def get_token(spotty):
    # get authentication token for api - prefer cached version
    token_info = None
    try:
        if spotty.playback_supported:
            # try to get a token with spotty
            token_info = request_token_spotty(spotty, use_creds=False)
            if token_info:
                spotty.get_username() # save current username in cached spotty creds
            if not token_info:
                token_info = request_token_spotty(spotty, use_creds=True)
        else:
            # request new token with web flow
            token_info = request_token_web()
    except Exception as exc:
        log_exception("utils.get_token", exc)
        token_info = None
    if not token_info:
        log_msg("Couldn't request authentication token. Username/password error ? "
                "If you're using a facebook account with Spotify, "
                "make sure to generate a device account/password in the Spotify accountdetails.")
    return token_info 
开发者ID:kodi-community-addons,项目名称:plugin.audio.spotify,代码行数:24,代码来源:utils.py

示例9: __init__

# 需要导入模块: import spotipy [as 别名]
# 或者: from spotipy import Spotify [as 别名]
def __init__(self):
        self.addon = xbmcaddon.Addon(id=ADDON_ID)
        self.win = xbmcgui.Window(10000)
        self.kodimonitor = xbmc.Monitor()
        self.spotty = Spotty()

        # spotipy and the webservice are always prestarted in the background
        # the auth key for spotipy will be set afterwards
        # the webserver is also used for the authentication callbacks from spotify api
        self.sp = spotipy.Spotify()
        self.connect_player = ConnectPlayer(sp=self.sp, spotty=self.spotty)

        self.proxy_runner = ProxyRunner(self.spotty)
        self.proxy_runner.start()
        webport = self.proxy_runner.get_port()
        log_msg('started webproxy at port {0}'.format(webport))

        # authenticate at startup
        self.renew_token()

        # start mainloop
        self.main_loop() 
开发者ID:kodi-community-addons,项目名称:plugin.audio.spotify,代码行数:24,代码来源:main_service.py

示例10: user_playlist_remove_specific_occurrences_of_tracks

# 需要导入模块: import spotipy [as 别名]
# 或者: from spotipy import Spotify [as 别名]
def user_playlist_remove_specific_occurrences_of_tracks(
            self, user, playlist_id, tracks, snapshot_id=None):
        ''' Removes all occurrences of the given tracks from the given playlist

            Parameters:
                - user - the id of the user
                - playlist_id - the id of the playlist
                - tracks - an array of objects containing Spotify URIs of the tracks to remove with their current positions in the playlist.  For example:
                    [  { "uri":"4iV5W9uYEdYUVa79Axb7Rh", "positions":[2] },
                       { "uri":"1301WleyT98MSxVHPZCA6M", "positions":[7] } ]
                - snapshot_id - optional id of the playlist snapshot
        '''

        plid = self._get_id('playlist', playlist_id)
        ftracks = []
        for tr in tracks:
            ftracks.append({
                "uri": self._get_uri("track", tr["uri"]),
                "positions": tr["positions"],
            })
        payload = {"tracks": ftracks}
        if snapshot_id:
            payload["snapshot_id"] = snapshot_id
        return self._delete("users/%s/playlists/%s/tracks" % (user, plid),
                            payload=payload) 
开发者ID:kodi-community-addons,项目名称:plugin.audio.spotify,代码行数:27,代码来源:client.py

示例11: categories

# 需要导入模块: import spotipy [as 别名]
# 或者: from spotipy import Spotify [as 别名]
def categories(self, country=None, locale=None, limit=20, offset=0):
        ''' Get a list of new album releases featured in Spotify

            Parameters:
                - country - An ISO 3166-1 alpha-2 country code.
                - locale - The desired language, consisting of an ISO 639
                  language code and an ISO 3166-1 alpha-2 country code, joined
                  by an underscore.

                - limit - The maximum number of items to return. Default: 20.
                  Minimum: 1. Maximum: 50

                - offset - The index of the first item to return. Default: 0
                  (the first object). Use with limit to get the next set of
                  items.
        '''
        return self._get('browse/categories', country=country, locale=locale,
                         limit=limit, offset=offset) 
开发者ID:kodi-community-addons,项目名称:plugin.audio.spotify,代码行数:20,代码来源:client.py

示例12: category_playlists

# 需要导入模块: import spotipy [as 别名]
# 或者: from spotipy import Spotify [as 别名]
def category_playlists(self, category_id=None, country=None, limit=20,
                           offset=0):
        ''' Get a list of new album releases featured in Spotify

            Parameters:
                - category_id - The Spotify category ID for the category.

                - country - An ISO 3166-1 alpha-2 country code.

                - limit - The maximum number of items to return. Default: 20.
                  Minimum: 1. Maximum: 50

                - offset - The index of the first item to return. Default: 0
                  (the first object). Use with limit to get the next set of
                  items.
        '''
        return self._get('browse/categories/' + category_id + '/playlists',
                         country=country, limit=limit, offset=offset) 
开发者ID:kodi-community-addons,项目名称:plugin.audio.spotify,代码行数:20,代码来源:client.py

示例13: __init__

# 需要导入模块: import spotipy [as 别名]
# 或者: from spotipy import Spotify [as 别名]
def __init__(self):
        try:
            self.addon = xbmcaddon.Addon(id=ADDON_ID)
            self.win = xbmcgui.Window(10000)
            self.cache = SimpleCache()
            auth_token = self.get_authkey()
            if auth_token:
                self.parse_params()
                self.sp = spotipy.Spotify(auth=auth_token)
                self.userid = self.win.getProperty("spotify-username").decode("utf-8")
                self.usercountry = self.win.getProperty("spotify-country").decode("utf-8")
                self.local_playback, self.playername, self.connect_id = self.active_playback_device()
                if self.action:
                    action = "self." + self.action
                    eval(action)()
                else:
                    self.browse_main()
                    self.precache_library()
            else:
                xbmcplugin.endOfDirectory(handle=self.addon_handle)
        except Exception as exc:
            log_exception(__name__, exc)
            xbmcplugin.endOfDirectory(handle=self.addon_handle) 
开发者ID:kodi-community-addons,项目名称:plugin.audio.spotify,代码行数:25,代码来源:plugin_content.py

示例14: precache_library

# 需要导入模块: import spotipy [as 别名]
# 或者: from spotipy import Spotify [as 别名]
def precache_library(self):
        if not self.win.getProperty("Spotify.PreCachedItems"):
            monitor = xbmc.Monitor()
            self.win.setProperty("Spotify.PreCachedItems", "busy")
            userplaylists = self.get_user_playlists(self.userid)
            for playlist in userplaylists:
                self.get_playlist_details(playlist['owner']['id'], playlist["id"])
                if monitor.abortRequested():
                    return
            self.get_savedalbums()
            if monitor.abortRequested():
                return
            self.get_savedartists()
            if monitor.abortRequested():
                return
            self.get_saved_tracks()
            del monitor
            self.win.setProperty("Spotify.PreCachedItems", "done") 
开发者ID:kodi-community-addons,项目名称:plugin.audio.spotify,代码行数:20,代码来源:plugin_content.py

示例15: __next__

# 需要导入模块: import spotipy [as 别名]
# 或者: from spotipy import Spotify [as 别名]
def __next__(self):
        # For the most part, the buffer-filling thread should prevent the need for waiting here,
        # but wait exponentially (up to about 32 seconds) for it to fill before giving up.
        log_msg("Spotify radio track buffer asked for next item", xbmc.LOGDEBUG)
        attempts = 0
        while attempts <= 5:
            self._buffer_lock.acquire()
            if len(self._buffer) <= self.MIN_BUFFER_SIZE:
                self._buffer_lock.release()
                sleep_time = pow(2, attempts)
                log_msg("Spotify radio track buffer empty, sleeping for %d seconds" % sleep_time, xbmc.LOGDEBUG)
                time.sleep(sleep_time)
                attempts += 1
            else:
                track = self._buffer.pop(0)
                self._buffer_lock.release()
                log_msg("Got track '%s' from Spotify radio track buffer" % track["id"], xbmc.LOGDEBUG)
                return track
        raise StopIteration

    # Support both Python 2.7 & Python 3.0 
开发者ID:kodi-community-addons,项目名称:plugin.audio.spotify,代码行数:23,代码来源:plugin_content.py


注:本文中的spotipy.Spotify方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。