Я думаю, что мой запрос правильный, и если я просто возвращаю и распечатываю результат JSON, он, похоже, возвращает полезную информацию, но если я попытаюсь удалить идентификатор:
Код: Выделить всё
track_id = result["id"]
Код: Выделить всё
def search_for_track(token, artist_name, track_name):
url = "https://api.spotify.com/v1/search"
headers = get_auth_header(token)
query = f"?q=track:{track_name} artist:{artist_name}&type=track&limit=1"
query_url = url + query
result = get(query_url, headers=headers)
json_result = json.loads(result.content)["tracks"]
return (json_result)
ext = (".aiff", ".mp3", ".wma", ".ogg", ".flac", ".ape", \
".mpc", ".opus", ".tta", ".wv", ".ofr", ".ofs", \
".off", ".asf", ".vob", ".oga")
def open_dir():
dirname = filedialog.askdirectory()
for entry in os.scandir(dirname):
if entry.is_file() and entry.name.endswith(tuple(ext)):
#print(entry.path)
audio = mutagen.File(entry.path, easy=True)
artist = audio.get('artist', ['Unknown'])[0]
title = audio.get('title', ['Unknown'])[0]
token = get_token()
result = search_for_track(token, artist, title)
track_id = result["id"]
print(track_id)
Если я удалю ["id"] и запущу...
Код: Выделить всё
track_id = result
print(track_id)
Код: Выделить всё
PS C:\Users\seren\Desktop\Spotifyle> & C:\Users\seren\AppData\Local\Python\pythoncore-3.14-64\python.exe c:/Users/seren/Desktop/Spotifyle/main.py
{'href': 'https://api.spotify.com/v1/search?offset=0&limit=1&query=track%3AIsabella%20of%20Castile%20artist%3AStarfucker&type=track', 'limit': 1, 'next': None, 'offset': 0, 'previous': None, 'total': 0, 'items': [{'album': {'album_type': 'album', 'artists': [{'external_urls': {'spotify': 'https://open.spotify.com/artist/2Tz1DTzVJ5Gyh8ZwVr6ekU'}, 'href': 'https://api.spotify.com/v1/artists/2Tz1DTzVJ5Gyh8ZwVr6ekU', 'id': '2Tz1DTzVJ5Gyh8ZwVr6ekU', 'name': 'STRFKR', 'type': 'artist', 'uri': 'spotify:artist:2Tz1DTzVJ5Gyh8ZwVr6ekU'}], 'external_urls': {'spotify': 'https://open.spotify.com/album/4mBSeOEiQ4WgDaCnydb0tZ'}, 'href': 'https://api.spotify.com/v1/albums/4mBSeOEiQ4WgDaCnydb0tZ', 'id': '4mBSeOEiQ4WgDaCnydb0tZ', 'images': [{'height': 640, 'width': 640, 'url': 'https://i.scdn.co/image/ab67616d0000b273a42a9e3de0baca2e178d0c73'}, {'height': 300, 'width': 300, 'url': 'https://i.scdn.co/image/ab67616d00001e02a42a9e3de0baca2e178d0c73'}, {'height': 64, 'width': 64, 'url': 'https://i.scdn.co/image/ab67616d00004851a42a9e3de0baca2e178d0c73'}], 'is_playable': True, 'name': 'Starfucker', 'release_date': '2008-09-23', 'release_date_precision': 'day', 'total_tracks': 11, 'type': 'album', 'uri': 'spotify:album:4mBSeOEiQ4WgDaCnydb0tZ'}, 'artists': [{'external_urls': {'spotify': 'https://open.spotify.com/artist/2Tz1DTzVJ5Gyh8ZwVr6ekU'}, 'href': 'https://api.spotify.com/v1/artists/2Tz1DTzVJ5Gyh8ZwVr6ekU', 'id': '2Tz1DTzVJ5Gyh8ZwVr6ekU', 'name': 'STRFKR', 'type': 'artist', 'uri': 'spotify:artist:2Tz1DTzVJ5Gyh8ZwVr6ekU'}], 'disc_number': 1, 'duration_ms': 271026, 'explicit': False, 'external_ids': {'isrc': 'US36Y0810033'}, 'external_urls': {'spotify': 'https://open.spotify.com/track/4wj53ItvfETfYRs4zzmiPC'}, 'href': 'https://api.spotify.com/v1/tracks/4wj53ItvfETfYRs4zzmiPC', 'id': '4wj53ItvfETfYRs4zzmiPC', 'is_local': False, 'is_playable': True, 'name': 'Isabella of Castile', 'track_number': 11, 'type': 'track', 'uri': 'spotify:track:4wj53ItvfETfYRs4zzmiPC'}]}
PS C:\Users\seren\Desktop\Spotifyle>
Однако, если я запущу:
Код: Выделить всё
track_id = result["href"]
print(track_id)
Код: Выделить всё
PS C:\Users\seren\Desktop\Spotifyle> & C:\Users\seren\AppData\Local\Python\pythoncore-3.14-64\python.exe c:/Users/seren/Desktop/Spotifyle/main.py
https://api.spotify.com/v1/search?offset=0&limit=1&query=track%3AIsabella%20of%20Castile%20artist%3AStarfucker&type=track
PS C:\Users\seren\Desktop\Spotifyle>
Код: Выделить всё
track_id = result["id"]
print(track_id)
Код: Выделить всё
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\seren\AppData\Local\Python\pythoncore-3.14-64\Lib\tkinter\__init__.py", line 2093, in __call__
return self.func(*args)
~~~~~~~~~^^^^^^^
File "C:\Users\seren\AppData\Local\Python\pythoncore-3.14-64\Lib\site-packages\customtkinter\windows\widgets\ctk_button.py", line 554, in _clicked
self._command()
~~~~~~~~~~~~~^^
File "c:\Users\seren\Desktop\Spotifyle\main.py", line 86, in open_dir
track_id = result["id"]
~~~~~~^^^^^^
KeyError: 'id'
Код: Выделить всё
#setupgui
customtkinter.set_appearance_mode("dark")
customtkinter.set_default_color_theme("green")
root = customtkinter.CTk()
root.geometry("500x350")
frame = customtkinter.CTkFrame(master=root)
frame.pack(pady=20, padx=60, fill="both", expand=True)
label = customtkinter.CTkLabel(master=frame, text="Spotifyle", font=("Roboto", 24))
label.pack(pady=12, padx=10)
button = customtkinter.CTkButton(master=frame, text="Open Directory", command=open_dir)
button.pack(pady=12, padx=10)
root.mainloop()
Если я запрашиваю тип json_result, он возвращает dict.
Если я попробую это:
Код: Выделить всё
json_result = json.loads(result.content)["tracks"]
json_result['test'] = True
new_json = json.dumps(json_result, indent=2)
print(new_json)
Код: Выделить всё
PS C:\Users\seren\Desktop\Spotifyle> & C:\Users\seren\AppData\Local\Python\pythoncore-3.14-64\python.exe c:/Users/seren/Desktop/Spotifyle/main.py
{
"href": "https://api.spotify.com/v1/search?offset=0&limit=1&query=track%3AIsabella%20of%20Castile%20artist%3AStarfucker&type=track",
"limit": 1,
"next": null,
"offset": 0,
"previous": null,
"total": 1,
"items": [
{
"album": {
"album_type": "album",
"artists": [
{
"external_urls": {
"spotify": "https://open.spotify.com/artist/2Tz1DTzVJ5Gyh8ZwVr6ekU"
},
"href": "https://api.spotify.com/v1/artists/2Tz1DTzVJ5Gyh8ZwVr6ekU",
"id": "2Tz1DTzVJ5Gyh8ZwVr6ekU",
"name": "STRFKR",
"type": "artist",
"uri": "spotify:artist:2Tz1DTzVJ5Gyh8ZwVr6ekU"
}
],
"external_urls": {
"spotify": "https://open.spotify.com/album/4mBSeOEiQ4WgDaCnydb0tZ"
},
"href": "https://api.spotify.com/v1/albums/4mBSeOEiQ4WgDaCnydb0tZ",
"id": "4mBSeOEiQ4WgDaCnydb0tZ",
"images": [
{
"height": 640,
"width": 640,
"url": "https://i.scdn.co/image/ab67616d0000b273a42a9e3de0baca2e178d0c73"
},
{
"height": 300,
"width": 300,
"url": "https://i.scdn.co/image/ab67616d00001e02a42a9e3de0baca2e178d0c73"
},
{
"height": 64,
"width": 64,
"url": "https://i.scdn.co/image/ab67616d00004851a42a9e3de0baca2e178d0c73"
}
],
"is_playable": true,
"name": "Starfucker",
"release_date": "2008-09-23",
"release_date_precision": "day",
"total_tracks": 11,
"type": "album",
"uri": "spotify:album:4mBSeOEiQ4WgDaCnydb0tZ"
},
"artists": [
{
"external_urls": {
"spotify": "https://open.spotify.com/artist/2Tz1DTzVJ5Gyh8ZwVr6ekU"
},
"href": "https://api.spotify.com/v1/artists/2Tz1DTzVJ5Gyh8ZwVr6ekU",
"id": "2Tz1DTzVJ5Gyh8ZwVr6ekU",
"name": "STRFKR",
"type": "artist",
"uri": "spotify:artist:2Tz1DTzVJ5Gyh8ZwVr6ekU"
}
],
"disc_number": 1,
"duration_ms": 271026,
"explicit": false,
"external_ids": {
"isrc": "US36Y0810033"
},
"external_urls": {
"spotify": "https://open.spotify.com/track/4wj53ItvfETfYRs4zzmiPC"
},
"href": "https://api.spotify.com/v1/tracks/4wj53ItvfETfYRs4zzmiPC",
"id": "4wj53ItvfETfYRs4zzmiPC",
"is_local": false,
"is_playable": true,
"name": "Isabella of Castile",
"track_number": 11,
"type": "track",
"uri": "spotify:track:4wj53ItvfETfYRs4zzmiPC"
}
],
"test": true
}
PS C:\Users\seren\Desktop\Spotifyle>
Любая помощь будет очень признательна. Кажется, я не могу уложить в этом голову. Я могу только думать, что данные JSON/словарь Python хранятся неправильно.