我正在尝试通过基于游标的分页获取订户列表。这是我第一次使用基于游标的分页,所以我可能过于复杂了,希望您能确定!
这是我的功能供参考:
def get_subscribers():
subscribers = [] # Create empty list for appending collected
url = 'https://api.twitch.tv/helix/subscriptions'
token = refresh_token(config.refresh_token)
headers = {
'Client-id':config.client_id,
'Authorization': 'Bearer {}'.format(token)
}
params = {
'broadcaster_id':config.channel_id,
}
req = requests.request('GET', url, params=params, headers=headers)
response = req.json()
subs = response['data']
next = response['pagination']['cursor']
for sub in subs:
print('Appending {0} to Subscriber List.'.format(sub['user_name']))
subscribers.append(sub)
while subs is not None:
params = {
'broadcaster_id':config.channel_id,
'after':next
}
req = requests.request('GET', url, params=params, headers=headers)
response = req.json()
subs = response['data']
next = response['pagination']['cursor']
for sub in subs:
print('Appending {0} to Subscriber List.'.format(sub['user_name']))
subscribers.append(sub)
return subscribers
以下是第一个请求的示例响应:
{
"data": [
{
"broadcaster_id": "67961343",
"broadcaster_name": "xJOKERx",
"is_gift": false,
"plan_name": "Channel Subscription (xJOKERx): $24.99 Sub",
"tier": "3000",
"user_id": "67961343",
"user_name": "xJOKERx"
},
{
"broadcaster_id": "67961343",
"broadcaster_name": "xJOKERx",
"is_gift": false,
"plan_name": "Channel Subscription (xJOKERx)",
"tier": "1000",
"user_id": "147283917",
"user_name": "killming"
},
{
"broadcaster_id": "67961343",
"broadcaster_name": "xJOKERx",
"is_gift": false,
"plan_name": "Channel Subscription (xJOKERx)",
"tier": "1000",
"user_id": "100417968",
"user_name": "King_gilbster"
},
{
"broadcaster_id": "67961343",
"broadcaster_name": "xJOKERx",
"is_gift": false,
"plan_name": "Channel Subscription (xJOKERx)",
"tier": "1000",
"user_id": "81318617",
"user_name": "ParagonWing"
},
],
"pagination": {
"cursor": "eyJiIjpudWxsLCJhIjp7Ik9mZnNldCI6MjB9fQ"
}
}
以下是“最终”页面上的示例响应:
{
"data": [],
"pagination": {
"cursor": "eyJiIjp7Ik9mZnNldCI6MTYwfSwiYSI6eyJPZmZzZXQiOjIwMH19"
}
}
所以我正在做的是发出初始请求,然后说列表is not None
在使用最后一个光标作为偏移量的同时继续发出请求。
此问题是列表永远不会None
。停止while
循环可以满足什么条件?
我也欢迎不需要while
循环的替代方法。
答案 0 :(得分:2)
检查列表是否为空,而不是检查sub is None
:
while subs: # This checks for both None and empty
# do things