Python - 在循环中发出https请求时将项添加到列表中

时间:2016-10-04 03:09:04

标签: python for-loop python-requests spotipy

我在SPotify API内向for loop发出请求,如下所示:

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

我可以printt好,但如果我尝试return track_ids,控制台就不会给我任何回报。

日志告诉我:

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

看起来一遍又一遍地开始和结束连接都与它有关......或者我在这里错过了一些明显的东西?

如何解决此问题并设法构建我的track_ids list

1 个答案:

答案 0 :(得分:1)

track_ids范围在您的函数中。要打印列表,您可以这样做

track_ids = yourfunction()
print track_ids

OR

你可以使track_ids列表全局并在你的函数之外声明它。