data_garden data_garden - 2 months ago 12
Python Question

Python - Append items to a list while making https requests inside a loop

I am making requests to

SPotify API
inside a
for loop
, like so:

track_ids = []
#get track_ids
for track in random.sample(pitchfork_tracks, 10):
results = sp.search(q=track, type='track') #here I call Spotify endpoint
items = results['tracks']['items']
for t in items:
track_ids.append(t['uri'])
return track_ids


I can
print
every
t
alright, but if I try to
return
track_ids
, console returns me nothing.

Log tells me:

2016-10-03 23:55:49 [requests.packages.urllib3.connectionpool] INFO: Starting new HTTPS connection (1): accounts.spotify.com
2016-10-03 23:55:50 [requests.packages.urllib3.connectionpool] DEBUG: "POST /api/token HTTP/1.1" 200 None
2016-10-03 23:55:50 [requests.packages.urllib3.connectionpool] INFO: Starting new HTTPS connection (1): api.spotify.com
2016-10-03 23:55:50 [requests.packages.urllib3.connectionpool] DEBUG: "GET /v1/search?q=Rushes&limit=10&type=track&offset=0 HTTP/1.1" 200 None
2016-10-03 23:55:50 [requests.packages.urllib3.connectionpool] INFO: Starting new HTTPS connection (1): api.spotify.com
2016-10-03 23:55:51 [requests.packages.urllib3.connectionpool] DEBUG: "GET /v1/search?q=Opposite+House&limit=10&type=track&offset=0 HTTP/1.1" 200 None
2016-10-03 23:55:51 [requests.packages.urllib3.connectionpool] INFO: Starting new HTTPS connection (1): api.spotify.com


it looks like starting and ending connections over and over has something to do with it...or am I missing something obvious here?

how can I solve this and manage to build my
track_ids
list
?

Answer

track_ids scope is inside your function. To print list you can do like this

track_ids = yourfunction()
print track_ids

OR

you can make track_ids list global and declare it outside of your function.