繁体   English   中英

如何在 Spotipy 中确定播放列表是否有播放列表图像封面?

[英]How to find out if a playlist has a playlist image cover in Spotipy?

正如标题所说,我试图查看播放列表是否有播放列表图像封面,以便它不会尝试加载不存在的播放列表。

这是我的方法:

 currentPlaylist = spotifyObject.user_playlist(username, playlistManageURI)
     
        if ['images'][0] in currentPlaylist:
            playlistCover_url = currentPlaylist['images'][0]['url']
            image = QImage()
            image.loadFromData(requests.get(playlistCover_url).content)
            self.playlistCover.setScaledContents(True)
            self.playlistCover.setPixmap(QPixmap(image))
        else:
            print('Playlist Cover doesnt exist!')

虽然如果确实加载了具有图像封面的播放列表,但如果我尝试加载一个带有不存在的图像封面的播放列表,它会给我

IndexError: list index out of range

这是带有封面的播放列表的 currentPlaylist 的样子

{
    "collaborative": false,
    "description": "",
    "external_urls": {
        "spotify": "https://open.spotify.com/playlist/xxxxxxxx"
    },
    "followers": {
        "href": null,
        "total": 4
    },
    "href": "https://api.spotify.com/v1/playlists/xxxxxxxx?additional_types=track",
    "id": "xxxxxx",
    "images": [
        {
            "height": null,
            "url": "https://i.scdn.co/image/ab67706c0000bebbcab54ad44bbf6dd124838df1",
            "width": null
        }
    ],
    "name": "xxxxx",
    "owner": {
        "display_name": "xxxxx",
        "external_urls": {
            "spotify": "https://open.spotify.com/user/xxxxxxxx"
        },
        "href": "https://api.spotify.com/v1/users/xxxx",
        "id": "xxxxx",
        "type": "user",
        "uri": "spotify:user:xxxx"

这就是没有封面的样子(完全空白的播放列表)

{
    "collaborative": false,
    "description": "xxxx",
    "external_urls": {
        "spotify": "https://open.spotify.com/playlist/xxxxxx"
    },
    "followers": {
        "href": null,
        "total": 0
    },
    "href": "https://api.spotify.com/v1/playlists/xxxxxx?additional_types=track",
    "id": "xxxxxx",
    "images": [],
    "name": "xxxxxx",
    "owner": {
        "display_name": "xxxxx",
        "external_urls": {
            "spotify": "https://open.spotify.com/user/xxxxx"
        },
        "href": "https://api.spotify.com/v1/users/xxxx",
        "id": "xxxxxxxx",
        "type": "user",
        "uri": "xxxxxxx"

如果“images”总是存在于 currentPlaylist 中,无论 currentPlaylist['images'] 是否为空。

if currentPlaylist['images']: 
     ...

否则

if "images" in currentPlaylist and  currentPlaylist["images"]:
    ...

用这种用法解决了:

if currentPlaylist.get('images') == []:
            print('no image found in playlist!')
        else:
            print(['images'][0])
            playlistCover_url = currentPlaylist['images'][0]['url']
            image = QImage()
            image.loadFromData(requests.get(playlistCover_url).content)
            self.playlistCover.setScaledContents(True)
            self.playlistCover.setPixmap(QPixmap(image))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM