Twilio Python助手库 - 如何知道列表资源返回了多少页?
我正在尝试写一个简单的脚本,用Python的辅助库从Twilio下载通话详情信息。目前看来,我唯一的选择就是使用.iter()方法来获取子账户下所有的通话记录。这可能会是一个非常庞大的数字。
如果我使用.list()资源,似乎没有任何地方告诉我有多少页,所以我不知道该继续翻页多久才能获取到这个时间段内的所有通话记录。我是不是漏掉了什么?
这里有一些文档和代码示例: http://readthedocs.org/docs/twilio-python/en/latest/usage/basics.html
2 个回答
4
现在这个功能的说明不是很详细,但你可以用下面的API调用来翻页查看列表:
import twilio.rest
client = twilio.rest.TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
# iterating vars
remaining_messages = client.calls.count()
current_page = 0
page_size = 50 # any number here up to 1000, although paging may be slow...
while remaining_messages > 0:
calls_page = client.calls.list(page=current_page, page_size=page_size)
# do something with the calls_page object...
remaining_messages -= page_size
current_page += 1
你可以在调用 list()
这个函数的时候,传入 page
和 page_size
这两个参数,这样就能控制你看到哪些结果。我今天会更新说明,让这个更清楚。
1
正如评论中提到的,上面的代码没有用,因为 remaining_messages = client.calls.count() 总是返回 50,这样就没法用来分页,完全没用。
所以我最后只能尝试获取下一页,直到失败,这样做有点不太正规。这个库应该在列表资源中加入 numpages 以便于分页。
import twilio.rest
import csv
account = <ACCOUNT_SID>
token = <ACCOUNT_TOKEN>
client = twilio.rest.TwilioRestClient(account, token)
csvout = open("calls.csv","wb")
writer = csv.writer(csvout)
current_page = 0
page_size = 50
started_after = "20111208"
test = True
while test:
try:
calls_page = client.calls.list(page=current_page, page_size=page_size, started_after=started_after)
for calls in calls_page:
writer.writerow( (calls.sid, calls.to, calls.duration, calls.start_time) )
current_page += 1
except:
test = False