You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Boto3的get_paginator()时,是否仍需检查NextToken?

关于AWS Organizations获取所有账号ID的分页问题

我正在定义一个从AWS组织中获取所有账号ID的方法。若使用get_paginator('list_accounts'),是否可以不用检查NextToken?我看到过要么调用get_paginator()、要么用while循环检查NextToken的示例,但从未见过同时使用两者的示例。

完全不需要自己检查NextToken,boto3的分页器(get_paginator)已经帮你封装了所有分页逻辑——包括自动获取下一页的Token、循环请求直到所有结果返回。

你看到的两种写法是二选一的关系:

  • 使用分页器:自动处理全部分页流程,无需手动管理NextToken
  • 手动循环:自己编写while逻辑,判断返回结果中的NextToken是否存在,以此决定是否继续请求下一页

所以不会有同时使用两者的情况,因为分页器已经替你完成了手动循环要做的所有工作。

你提供的代码是正确的,它会自动遍历所有分页结果,收集所有账号ID:

def get_all_account_ids():
    org_client = boto3.client('organizations')
    paginator = org_client.get_paginator('list_accounts')
    page_iterator = paginator.paginate()

    account_ids = []
    for page in page_iterator:        
        for acct in page['Accounts']:
            print(acct['Id']) # print the account id

            # add to account_ids list
            account_ids.append(acct['Id'])

    return account_ids

内容的提问来源于stack exchange,提问作者Sreenivas Sama

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 09:31:04