0
# Network and Authentication
1
2
Network initialization, authentication methods, session management, and configuration options for PyLast. This covers the core infrastructure for accessing Last.fm and Libre.fm APIs with proper authentication and advanced configuration.
3
4
## Capabilities
5
6
### Network Initialization
7
8
Core network objects that serve as entry points to Last.fm and Libre.fm APIs, managing authentication, API communication, and configuration.
9
10
```python { .api }
11
class LastFMNetwork:
12
"""
13
Main entry point for Last.fm API access.
14
15
Args:
16
api_key (str): Last.fm API key
17
api_secret (str): Last.fm API secret
18
session_key (str, optional): Pre-generated session key
19
username (str, optional): Username for authentication
20
password_hash (str, optional): MD5 hash of password
21
token (str, optional): Authentication token to retrieve session
22
"""
23
def __init__(self, api_key="", api_secret="", session_key="", username="", password_hash="", token=""): ...
24
25
def get_artist(self, artist_name: str) -> Artist: ...
26
def get_track(self, artist: str, title: str) -> Track: ...
27
def get_album(self, artist: str, title: str) -> Album: ...
28
def get_user(self, username: str) -> User: ...
29
def get_authenticated_user(self) -> AuthenticatedUser: ...
30
def get_country(self, country_name: str) -> Country: ...
31
def get_tag(self, name: str) -> Tag: ...
32
33
class LibreFMNetwork:
34
"""
35
Preconfigured network for Libre.fm API access.
36
37
Args:
38
api_key (str): Libre.fm API key
39
api_secret (str): Libre.fm API secret
40
session_key (str, optional): Pre-generated session key
41
username (str, optional): Username for authentication
42
password_hash (str, optional): MD5 hash of password
43
"""
44
def __init__(self, api_key="", api_secret="", session_key="", username="", password_hash=""): ...
45
```
46
47
### Session Management
48
49
Authentication and session key generation for secure API access, supporting multiple authentication flows.
50
51
```python { .api }
52
class SessionKeyGenerator:
53
"""
54
Handles session key generation for authentication.
55
56
Args:
57
network: Network instance (LastFMNetwork or LibreFMNetwork)
58
"""
59
def __init__(self, network): ...
60
61
def get_web_auth_url(self) -> str:
62
"""Generate web authentication URL for user authorization."""
63
64
def get_web_auth_session_key(self, url: str, token: str = None) -> str:
65
"""
66
Get session key from web authentication.
67
68
Args:
69
url (str): Authentication URL
70
token (str, optional): Authentication token
71
72
Returns:
73
str: Session key for API access
74
"""
75
76
def get_web_auth_session_key_username(self, url: str = None, token: str = None) -> tuple[str, str]:
77
"""
78
Get session key and username from web authentication.
79
80
Args:
81
url (str, optional): Authentication URL
82
token (str, optional): Authentication token
83
84
Returns:
85
tuple[str, str]: (session_key, username)
86
"""
87
88
def get_session_key(self, username: str, password_hash: str) -> str:
89
"""
90
Get session key from username and password hash.
91
92
Args:
93
username (str): User's username
94
password_hash (str): MD5 hash of user's password
95
96
Returns:
97
str: Session key for API access
98
"""
99
```
100
101
### Network Configuration
102
103
Advanced configuration options for proxy support, caching, and rate limiting.
104
105
```python { .api }
106
# Network configuration methods (available on LastFMNetwork and LibreFMNetwork)
107
108
def enable_proxy(self, proxy: str | dict) -> None:
109
"""
110
Enable proxy support for API requests.
111
112
Args:
113
proxy (str | dict): Proxy server URL string or dict of proxy settings.
114
Multiple proxies can be passed as a dict for different protocols.
115
"""
116
117
def disable_proxy(self) -> None:
118
"""Disable proxy support."""
119
120
def is_proxy_enabled(self) -> bool:
121
"""Returns True if web proxy is enabled."""
122
123
def enable_caching(self, file_path: str = None) -> None:
124
"""
125
Enable caching of web service calls.
126
127
Args:
128
file_path (str, optional): Path to cache file. If None, uses temporary file.
129
"""
130
131
def disable_caching(self) -> None:
132
"""Disable caching of web service calls."""
133
134
def is_caching_enabled(self) -> bool:
135
"""Returns True if caching is enabled."""
136
137
def enable_rate_limit(self) -> None:
138
"""Enable rate limiting to comply with Last.fm API terms (0.2s between calls)."""
139
140
def disable_rate_limit(self) -> None:
141
"""Disable rate limiting for faster API calls."""
142
143
def is_rate_limited(self) -> bool:
144
"""Return True if web service calls are rate limited."""
145
```
146
147
### MusicBrainz Integration
148
149
Lookup music objects using MusicBrainz IDs for precise identification.
150
151
```python { .api }
152
def get_artist_by_mbid(self, mbid: str) -> Artist:
153
"""
154
Get artist by MusicBrainz ID.
155
156
Args:
157
mbid (str): MusicBrainz artist ID
158
159
Returns:
160
Artist: Artist object
161
"""
162
163
def get_album_by_mbid(self, mbid: str) -> Album:
164
"""
165
Get album by MusicBrainz ID.
166
167
Args:
168
mbid (str): MusicBrainz album ID
169
170
Returns:
171
Album: Album object
172
"""
173
174
def get_track_by_mbid(self, mbid: str) -> Track:
175
"""
176
Get track by MusicBrainz ID.
177
178
Args:
179
mbid (str): MusicBrainz track ID
180
181
Returns:
182
Track: Track object
183
"""
184
```
185
186
## Usage Examples
187
188
### Basic Network Setup
189
190
```python
191
import pylast
192
193
API_KEY = "your_api_key"
194
API_SECRET = "your_api_secret"
195
196
# Simple setup without authentication (read-only access)
197
network = pylast.LastFMNetwork(api_key=API_KEY, api_secret=API_SECRET)
198
199
# Setup with username/password authentication
200
username = "your_username"
201
password_hash = pylast.md5("your_password")
202
203
network = pylast.LastFMNetwork(
204
api_key=API_KEY,
205
api_secret=API_SECRET,
206
username=username,
207
password_hash=password_hash
208
)
209
```
210
211
### Web Authentication Flow
212
213
```python
214
import pylast
215
import webbrowser
216
import time
217
218
network = pylast.LastFMNetwork(api_key=API_KEY, api_secret=API_SECRET)
219
220
# Generate authentication URL
221
skg = pylast.SessionKeyGenerator(network)
222
auth_url = skg.get_web_auth_url()
223
224
print(f"Please authorize this application: {auth_url}")
225
webbrowser.open(auth_url)
226
227
# Wait for user authorization and get session key
228
input("Press Enter after authorizing the application...")
229
230
try:
231
session_key = skg.get_web_auth_session_key(auth_url)
232
network.session_key = session_key
233
print("Authentication successful!")
234
except pylast.WSError as e:
235
print(f"Authentication failed: {e}")
236
```
237
238
### Network Configuration
239
240
```python
241
# Enable caching for better performance
242
network.enable_caching("/path/to/cache/file")
243
244
# Enable proxy support
245
network.enable_proxy("proxy.example.com", 8080)
246
247
# Enable rate limiting (recommended for production)
248
network.enable_rate_limit()
249
250
# Configure for Libre.fm instead
251
libre_network = pylast.LibreFMNetwork(
252
api_key=LIBRE_API_KEY,
253
api_secret=LIBRE_API_SECRET,
254
username=username,
255
password_hash=password_hash
256
)
257
```
258
259
## Authentication Types
260
261
PyLast supports multiple authentication methods:
262
263
1. **No Authentication**: Read-only access to public data
264
2. **Username/Password**: Direct authentication with user credentials
265
3. **Session Key**: Pre-generated session key for API access
266
4. **Web Authentication**: OAuth-style flow for user authorization
267
5. **Token-based**: Authentication using temporary tokens
268
269
Choose the appropriate method based on your application's security requirements and user experience needs.