-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlastfm_client.py
78 lines (70 loc) · 2.69 KB
/
lastfm_client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import requests
from flask_login import current_user
class LastFmClient:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = 'http://ws.audioscrobbler.com/2.0/'
def search_album(self, search_string):
params = {
'method': 'album.search',
'album': search_string,
'api_key': self.api_key,
'format': 'json'
}
response = requests.get(self.base_url, params=params)
if response.status_code == 200:
data = response.json()['results']['albummatches']['album']
print("API Data:", data)
return response.json()['results']['albummatches']['album']
else:
print("Request URL:", response.url)
print("Failed to retrieve data:", response.status_code, response.json())
return None
def search_art(self, search_string):
params = {
'method': 'artist.search',
'artist': search_string,
'api_key': self.api_key,
'format': 'json'
}
response = requests.get(self.base_url, params=params)
if response.status_code == 200:
response_data = response.json()
print("Full API Response:", response_data)
try:
artists = response_data['results']['artistmatches']['artist']
print("API Data:", artists)
return artists
except KeyError:
print("KeyError: Could not find the expected keys in the response.")
return None
else:
print("Request URL:", response.url)
print("Failed to retrieve data:", response.status_code, response.json())
return None
def get_top_albums(self, period='overall', limit=50, page=1):
if not current_user.is_authenticated:
return []
username = current_user.username
params = {
'method': 'chart.getTopTracks',
'user': username,
'period': period,
'limit': limit,
'page': page,
'api_key': self.api_key,
'format': 'json'
}
response = requests.get(self.base_url, params=params)
print("Request URL:", response.url)
print("Response Content:", response.content)
if response.status_code == 200:
data = response.json().get('tracks', {}).get('track', [{}])
print("API Data:", data)
return data
elif response.status_code == 404:
print("User not found:", response.json())
return []
else:
print("Failed to retrieve data:", response.status_code, response.json())
return []